-2

I want to read the matrix from file and store it in an array. But the array is storing only the last value of matrix. Can anyone explain this please?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    FILE *fp, *fp1;
    int n = 0, i, j, a[4][4], b[16];
    fp = fopen("Output.txt", "r");
    if (fp == NULL) {
        printf("\nError; Cannot open file");
        exit(1);
    }
    while (!feof(fp)) {
        i = 0;
        fscanf(fp, "%d", &n);//reads the file containing matrix
        b[i] = n;//this part is not working
        printf("%d\n", n);
        i++;
    }
    fclose(fp);
    fp1 = fopen("Output2.txt", "w");
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            fprintf(fp1, "%d\t", a[i][j] * 2);
        }
        fprintf(fp1, "\n");//creates file of altered matrix
    }
    fclose(fp1);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189

1 Answers1

3

Your input loop is incorrect:

  • you reset i to 0 at the beginning of each iteration
  • you use an incorrect test: while (!feof(fp)). Learn here why: Why is “while ( !feof (file) )” always wrong? . You should instead test the array index against the array length and check if fscanf() succeeds at reading the next value.

Here is a corrected version:

for (i = 0; i < 16; i++) {
    if (fscanf(fp,"%d",&n) != 1) { //reads the file containing matrix
        fprintf(stderr, "invalid input\n");
        exit(1);
    }
    b[i] = n;
    printf("%d\n", n);
}

Note also that you do not read the values into the 2D matrix, so the output loop has undefined behavior because a is uninitialized.

Here is a improved version:

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *fp;
    int i, j, a[4][4];

    fp = fopen("Output.txt", "r");
    if (fp == NULL) {
        fprintf(stderr, "Error: Cannot open file Output.txt for reading\n");
        exit(1);
    }
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            if (fscanf(fp, "%d", &a[i][j]) != 1) {
                fprintf(stderr, "invalid input for a[%d][%d]\n", i, j);
                fclose(fp);
                exit(1);
            }
        }
    }
    fclose(fp);

    fp1 = fopen("Output2.txt", "w");
    if (fp1 == NULL) {
        fprintf(stderr, "Error: Cannot open file Output2.txt for writing\n");
        exit(1);
    }
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            fprintf(fp1, "%d\t", a[i][j] * 2);
        }
        fprintf(fp1, "\n");
    }
    fclose(fp1);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189