I want to read a large (unknown number of columns) from file to 2d array using C. Number of columns is constant for each line. Columns are separated by one space (' ') in the file.
I tried doing it with the loop inside the loop, but without success. I also managed to write a code counting the number of columns, but this is as far as I am. I am a beginner at programming, so any help would be appreciated.
Data are in the txt format separated by space character, and each line has even number of columns. I tried to read all the data to 2D array since I came to the conclusion that this format would be easier to use later.
The code I use is below
int readData(char *filename, FILE *f) {
int lines;
int count = 0;
float dataArray [lines][count];
int i,j;
char c;
f = fopen(filename, "r");
if (f == NULL) return -1;
for (c = getc(f); c != '\n'; c = getc(f)) {
if (c == '\t')
count++;
}
printf("Your file %s consists of %d columns\n", filename, count);
printf("Set the lenght: ");
scanf("%d", &lines);
for(int i=0;i<lines;i++){
for(int j=0;j<count;j++){
fscanf(f,"%f", &dataArray[i][j]);
}
}
for (i=0; i<lines; i++) {
for (j=0;j<count;j++)c{
printf("%.3f",dataArray[i][j]);
}
printf("\n");
}
printf("\n");
fclose(f);
return 0;
}
int main (int argc, char *argv[], char filename[512]) {
FILE *f;
printf("Enter the file name: ");
if (scanf("%s", filename) != 1) {
printf("Error in the filename\n");
return -1;
}
if (readData(filename, f) == -1) {
printf("Error in file opening\n");
return -1;
}
return 0;
}
The data input is like this:
217,526 299,818 183,649 437,536 213,031 251 263,275 191,374 205,002 193,645 255,846 268,866 2,516\n
229,478 304,803 184,286 404,491 210,738 237,297 279,272 189,44 202,956 204,126 242,534 276,068 2,163\n
but out of it i get an array of a desirable length, but the rest is all wrong, looking like this:
225.0000000.000000-1798259351694660865572287994621067264.0000000.0000000.0000000.0000000.0000000.0000000.0000000.00000014037667868815752572174336.0000000.000000\n
225.0000000.000000-1798259351694660865572287994621067264.0000000.0000000.0000000.0000000.0000000.0000000.0000000.00000014037667868815752572174336.0000000.000000\n
Your destination array must be DYNAMIC. You are creating an static array using uninitialized data:
float dataArray [lines][count]; // line is not initialized, and count = 0
Change that to this:
Declaration:
float dataArray**;
Initialization:
// only after setting count and lines
dataArray = malloc(lines * sizeof(float*));
for (int i = 0; i < lines; ++i) {
dataArray[i] = malloc(count * sizeof(float));
}
Cleanup: You must release the memory allocated for dataArray
when it's no longer needed:
for (int i = 0; i < lines; ++i) {
free(dataArray[i]);
}
free(dataArray);
dataArray = NULL; // It's good to get used to nullify vars after deleting them