Reputation: 3661
I am writing a function in c that, given the dimension d
of a square matrix stored in a filepath f
, reads the integers into a 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 i = 0;
fp = fopen(f, "r");
while (i<d*d) {
fscanf(fp, "%d ", &m[i]);
i++;
printf("%d\n", m[i]);
}
}
However when I run this function, all my outputs are 0:
Dimension: 3 Filename: sample.dat
0
0
0
0
0
0
0
0
0
What is it that I am doing wrong here?
Upvotes: 0
Views: 1997
Reputation: 53006
Many problems in very little code
fscanf()
succeeded.i
before printf()
thus printing the next element instead of current.fclose()
the 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 to open `%s' for reading\n", path);
return; //
}
for (int i = 0 ; ((i < dimension * dimension) && (fscanf(file, "%d ", &data[i]) == 1)) ; ++i)
printf("data[%d] = %d\n", i, data[i]);
fclose(file);
}
Upvotes: 1