i have to fill my record with input by file. The record has 4 field, but the problems come out witj the string only. i use strtok to divide mi string into 4 parts but only the string seems like every cells of the array point to the last call of strtok, example and code below:
int GetRecord(char* file_name,Record* A){
FILE *fd = fopen(file_name,"rt");int i=0;
char* st=(char*)malloc(100*sizeof(char*));
if(fd == NULL){
printf("GetRecord:path file doesn't exist");
exit(EXIT_FAILURE);
};
while(!feof(fd)){
fscanf(fd,"%s\n",st);
A[i].id=atoi(strtok(st, ";"));
A[i].field1 =strtok(NULL, ";");printf("\nString: %s",A[i].field1);
A[i].field2 = atoi(strtok(NULL, ";"));
A[i].field3 = atof(strtok(NULL, ";"));
i++;
}
fclose(fd);
return i;
}
int main(int argc,char* argv[]){
OrderedArray* b = ordered_array_create();
Record* A = (Record*)malloc(START_CAPACITY_RECORD*sizeof(Record));
int dim = GetRecord("TEST.csv",A);
Record *B;
for(int i = 0; i<dim;i++){
ordered_array_add(b,&A[i]);
B=(Record*)ordered_array_get(b,i);
printf("\nValore %d field1 %s field2 %i field3 %f position %d",A[i].id,A[i].field1,A[i].field2,A[i].field3,i);
}
ordered_array_free(b);
free(A);
}
My file:
15;Matteo;21;79.7;
14;Serena;20;60.5;
The Output:
String: Matteo
String: Serena
Valore 15 field1 Serena field2 21 field3 79.699997 position 0
Valore 14 field1 Serena field2 20 field3 60.500000 position 1