c - 如何使用C从文件中读取二维数组?

标签 c stdio

我尝试过:

void read_grid_from_file( int** grid, const size_t row, const size_t column, FILE* inf ) {
    size_t x, y;
    for( x = 0; x < row; ++x ) {
        for( y = 0; y < column; ++y ) {
            fscanf( inf, "%d", &grid[x][y] );
            printf( "%d ", grid[x][y] );
        }
        printf( "\n" ); 
    }
}

int main( int argc, char *argv[] ) {
    FILE* inf; // input file stream
    FILE* outf; // output file stream
    char pbm_name[20]; 
    size_t row = 0;
    size_t column = 0;
    /*
    if( argc != 3 ) {
        prn_info( argv[0] );
        exit( 1 );
    }
    */
    inf = fopen( "infile.txt" , "r" );
    outf = fopen( "outfile.txt", "w" );
    fgets( pbm_name, 20, inf ); 
    fscanf( inf, "%d", &row );
    fscanf( inf, "%d", &column );
    int** grid = allocate_memory_for_grid( row, column );
    read_grid_from_file( grid, row, column, inf );
    show_grid( grid, row, column ); //for debugging
}

输入文件是:

P1
12 14
1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1

输出为:

1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 1 1 0 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0 0 0 0
0 0 1 1 1 1 1 1 1 1 0 0 0 0
1 1 1 1 1 1 1 1 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 1 1 0 0 0 0 0 0
0 0 0 0 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
Press any key to continue . . .

这个矩阵是从哪里来的?

最佳答案

我猜你刚刚颠倒了你的行和列。输入文件中有 12 列和 14 行,而在代码中,您将行读取为列,将列读取为行。

关于c - 如何使用C从文件中读取二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4352653/

相关文章:

python - ctypes python 中的浮点指针并传递结构指针

c - C语言数组上界检查

Java + Eclipse : Synchronize stdout and stderr

c - 字符数组的工作原理

c++ - C++ 包装器库中的 OpenSSL Fips 如何操作?错误 : fingerprint does not match

c - 如何静态且高效地实现两个节点数组?

c - 为什么线程 id 不唯一?

linux - 检测后台操作

c - 如何查找文本文件中一行的长度?

c++ - #define NDEBUG 似乎不起作用