I'm trying to write a function in C which reads from a file some values separated by commas, on each line there are 4 values, the last one is an integer and I want to put them in a allocated space. When I'm trying to read them from the memory in while loop they are just fine but from the for loop or from outside of the function I get just the last line of the file multiple times in few cases they miss some characters. I'm new to C but I assume that it has something to do with strtok()
function.
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
char * foo;
char * bar;
char * baz;
int qux;
}structure;
char * readFile(const char * filename, structure * array){
const int maxstring=100;
FILE * fr=fopen(filename,"r");
char * rc;
char buf[maxstring];
while(( rc = fgets(buf, maxstring, fr) )) {
array->foo=strtok (buf,",");
array->bar=strtok (NULL,",");
char *aux=strtok (NULL,",");
array->qux=atol(strtok (buf,","));
array->baz=strtok(aux,"\n");
printf("%s,%s,%s,%d\n",array->foo,array->bar,
array->baz,array->qux);
array++;
}
array=array-9;
for (int i=0;i<10;i++){
printf("%s,%s,%s,%d\n",array->foo,array->bar,
array->baz,array->qux);
array++;
}
return "Success";
}
int main(){
structure * array=malloc(100*sizeof(structure));
readFile("repository.txt",array);
free(array);
return 0;
}