I have looked through similarly worded questions and had no luck with my problem. I am aiming to read in a matrix from a text file in C, and then perform operations on it. Currently, I am writing a function to read in the matrix. The text files always have the format
# Comment
# Comment
matrix NROWS NCOLS
DATA DATA DATA
DATA DATA DATA etc
end
so for a 3x4 matrix:
# Comment
# Comment
matrix 3 4
7.16669652013 8.21223145665 8.78374366033 5.87828106521
7.32124040244 4.30552353817 1.67905652974 3.91825198378
7.28717047595 3.83999063812 5.53693148121 6.03363152874
end
My function currently is:
void read_matrix(char *filename, int rows, int cols) {
char *status;
char line[MAX_FILE_LINE_SIZE];
int line_no = 1;
char *data_line;
double matrix[rows][cols];
printf("Reading Matrix...\n");
FILE *inf = fopen(filename, "r");
if (!inf) {
fprintf(stderr, "Error, could not open file '%s'\n", filename);
exit(1);
}
status = fgets(line, sizeof(line), inf);
while (status) {
status = fgets(line, sizeof(line), inf);
///printf("%i: %s", line_no, line);
if (line_no >= 3 && line_no < 3+rows) {
int i=0;
data_line = strtok(line, " \t");
while (data_line != NULL) {
matrix[line_no-3][i] = atof(data_line);
data_line = strtok(NULL, " \t");
i++;
}
}
line_no ++;
}
printf("PRINT MATRIX\n");
for (int z=0; z<rows; z++) {
for (int j=0; j<cols; j++) {
printf("matrix[%i][%i] = %f\n",z, j, matrix[z][j]);
}
}
fclose(inf);
}
which works great, and so at the end of the function I have all the data saved into a 2D array matrix[rows][cols]
.
However I am completely stumped on how to then use this function in main, as outside of the function the variable is no longer in scope. Any help would be very appreciated.