首页 > 解决方案 > 从C中的文件中读取矩阵

问题描述

我想从文件中读取矩阵并将其存储在一个数组中。但是数组只存储矩阵的最后一个值。任何人都可以解释一下吗?

#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;
}

标签: cfile-handling

解决方案


您的输入循环不正确:

  • 您在每次迭代开始时重置i0
  • 您使用了不正确的测试:while (!feof(fp))。在这里了解原因:为什么“while (!feof (file))”总是错误的?. 相反,您应该根据数组长度测试数组索引,并检查是否fscanf()成功读取下一个值。

这是一个更正的版本:

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);
}

另请注意,您没有将值读入 2D 矩阵,因此输出循环具有未定义的行为,因为a未初始化。

这是一个改进的版本:

#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;
}

推荐阅读