c - 如何在C中将文件中的网格读入二维数组?

标签 c multidimensional-array file-io file-handling

我尝试将文件中的网格读取到二维数组中。该程序编译没有任何错误。这是代码:

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

    FILE* openFile(FILE* file, char* name, char* mode) {
        file = NULL;
        file = fopen(name, mode);
        if(file == NULL) {
            printf("Could not open a file!\n");
            exit(1);
        } else {
            printf("File was opened/created successfully!\n\n");
        }

        return file;
    }

    int main() {
        FILE* file;
        file = openFile(file, "a.txt", "r");

        char c;
        int x, row, column;
        x = row = column = 0;

        int array[2][2];
        for(int i = 0; i < 2; i++) {
            for(int j = 0; j < 2; j++) {
                array[i][j] = 0;
            }
        }

        while(!feof(file) && (c = fgetc(file))) {
            if(c == '\n') {
                row++;
            }

            if(c != '\n' && c!= '\r') {
                x = atoi(&c);
                if(array[row][column] == 0) {
                    array[row][column] = x;
                    printf("array[%d][%d] = %d\n", row, column, array[row][column]);
                    printf("row = %d\n", row);
                    printf("column = %d\n\n", column);
                    column++;
                }
            }
        }

        for(int i = 0; i < row; i++) {
            for(int j = 0; j < column; j++) {
                printf("array[%d][%d] = %d\n", i, j, array[i][j]);
            }
            printf("\n");
        }

        fclose(file);
        return 0;
    }

txt 文件:

    02
    46

程序的输出:

    File was opened/created successfully!

    array[0][0] = 0
    row = 0
    column = 0

    array[0][1] = 2
    row = 0
    column = 1

    array[0][0] = 0
    array[0][1] = 2

看起来它只读取第一行,然后 feof() 返回它已到达末尾。我访问了一些网站试图了解问题所在。

谁能解释一下我犯的错误在哪里并显示正确的解决方案?

最佳答案

更改行时您没有重置列号。文件中的第二行保存在 array[1][2] 和 array[1][3] 中,但不显示它。

while(!feof(file) && (c = fgetc(file))) {
    if(c == '\n') {
        row++;
        column = 0;
    }

这通常可以工作。

关于c - 如何在C中将文件中的网格读入二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38585425/

相关文章:

c# - 从 View (.cshtml) 访问 viewbag 值

c++ - 我想从文件中读取数据 block 并将其存储在 vector<string> buf 中。我究竟做错了什么?

使用 2 个视频卡进行 CUDA C 编程

c++ - 3点之间的角度?

ruby - 在 Ruby 中实现数组的 to_s

c# - 使用图片框和矩形制作棋盘,如何初始化?

java - 是否可以使用 JAVA 从文件中读取/写入位?

c# - 如何将文件中特定偏移量的字节复制到特定偏移量的另一个文件?

c - 关于epoll_wait的返回机制

c# - 如何顺利开发C#/.NET的C库?