开发者

How to read an 2 dimensional array from file using C?

I tried:

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
}

The input file is:

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

The output is:

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 . . .

Where did that matrix come from?


I guess you have just reversed your row and column. There are 12 columns and 14 rows in your input file, whereas in your code, you are reading rows as columns and columns as rows.


You read row and then column. Should be vice versa, column then row.


Sorry guys, I think I got it, the row and column from the text file were reversed!!


You appear to be reading a .pbm file. You may want to consider using the netpbm library, if the license is suitable for your purposes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜