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

  1. you never check whether file did open.
  2. you never check whether fscanf() succeeded.
  3. you increment i before printf() printing next element instead of current.
  4. 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

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -