I found this code to work...but read the comments \\
and note the comment on variable length arrays (VLA).
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
FILE *input;
int i, j, temp, dim;
const char inp_fn[]="matrix.dat";
/*Open File*/
input = fopen(inp_fn, "r");
dim = 0;
while (EOF != (temp = fgetc(input)))
{
if (temp=='\n')
{
++dim;
}
}
float fullmatrix[dim][dim]; // define fullmatrix after dim is known
// we close and reopen the file. We could also move back to the beginning of the file.
fclose(input);
printf("%d\n", dim);
input = fopen(inp_fn, "r");
// Probably not the safest way...we just assume that the file has not change after we
// determined dim
for (i=0; i<dim; i++)
{
for(j=0; j<dim; j++)
{
fscanf(input, "%f", &fullmatrix[i][j]);
printf("%f ", fullmatrix[i][j]);
}
printf("\n");
}
fclose(input);
return(0);
}
Example output:
3
1.000000 2.000000 3.000000
4.000000 5.000000 6.000000
7.000000 8.000000 9.000000