简体   繁体   中英

How to read matrix of integers from file in C?

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?

Many problems in very little code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM