My method reads an input text of vectors with the following format:
57.0000,-7.4703,-0.3561
81.0000,-4.6478,7.9474
69.0000,-8.3768,0.4391
18.0000,-4.9377,9.9903
62.0000,-5.8751,-6.6054
...
My attempt to read each vector and insert it to an array is as follows:
FILE *file;
int n = 1, dim, i=0;
char* str;
double ret;
double* X;
int c;
int com=0;
assert(argc==2 && "argc != 2");
file = fopen(argv[1], "r");
assert(file && "file is empty");
for(c = getc(file); c!= EOF; c = getc(file)){
if(c == '\n'){
n++;
}
else if(c==','){
com++;
}
}
dim = com/n +1;
char* str;
double ret;
double* X;
X = (double *)calloc(n*n, sizeof(double));
assert(X);
str = (char *)calloc(100, sizeof(char));
assert(str);
for(c = getc(file); c!= EOF; c = getc(file)){
if(c!=',' && c!= '\n'){
strcat(str, &c);
}
else{
ret = strtod(str, NULL);
X[i] = ret;
i++;
memset(str, 0, 100 * sizeof(char));
}
}
The problem is that when it gets to the last vector at each line, it reads each char and concatenates it with extra garbage into str. Any ideas how to solve this?