Hello,
I am working on a project in C which requires me to read in matrix values from a txt file. The first two lines are the number of rows and columns, and the rest is the actual matrix data.
For example, something like this:
2
2
1.0 2.0
3.0 4.0
The code I wrote is giving me some issues. Here's a snippet:
matrix read(char* file){
FILE *fp;
printf("check 1\n");
fp = fopen(file,"r");
printf("file opened\n");
// Make the new matrix
matrix result;
printf("matrix created\n");
int counter = 0;
int i;
int j;
int holdRows;
int holdColumns;
if(counter == 0)
{ // read in rows
fscanf(fp, "%li", holdRows);
printf("here is holdRows: %li\n", holdRows);
counter++;
}
if(counter == 1)
{ // read in columns
fscanf(fp, "%li", holdColumns);
printf("here is holdColumns: %li\n", holdColumns);
counter++;
// Now that I know the dimensions, make the matrix
result = newMatrix(holdRows, holdColumns);
}
// For the rest, read in the values
for(i = 0; i < holdRows; i++)
for(j = 0; j < holdColumns; j++)
fscanf(fp, "%lf", &result->matrixData[i][j]);
fclose(fp);
return result;
}
Whenever I run this, holdRows and holdColumns are not the values stored in the txt file. For example, I tried a 3X4 matrix, and it read that there was one row and three columns.
Can anyone tell me what I'm doing wrong?
Thanks :)