How to read matrix of integers from file in C? -
i writing function in c that, given dimension d
of square matrix stored in filepath f
, reads integers 1-dimensional array m
of size d*d.
a sample file sample.dat
may be:
10 20 30 12 24 36 1 2 3
my function is:
void readmatrix(int d, char *f, int *m) { file *fp; int = 0; fp = fopen(f, "r"); while (i<d*d) { fscanf(fp, "%d ", &m[i]); i++; printf("%d\n", m[i]); } }
however when run function, outputs 0:
dimension: 3 filename: sample.dat 0 0 0 0 0 0 0 0 0
what doing wrong here?
many problems in little code
- you never check whether file did open.
- you never check whether
fscanf()
succeeded. - you increment
i
beforeprintf()
printing next element instead of current. - you never
fclose()
open file.
correct way of maybe doing this
void readmatrix(int dimension, char *path, int *data) { file *file; file = fopen(path, "r"); if (file == null) { fprintf(stderr, "error: while trying open `%s' reading\n", path); return; // } (int = 0 ; ((i < dimension * dimension) && (fscanf(file, "%d ", &data[i]) == 1)) ; ++i) printf("data[%d] = %d\n", i, data[i]); fclose(file); }
Comments
Post a Comment