Wie zu Lesen ist ein 2-dimensionales array aus der Datei mit C?

Habe ich versucht:

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
}

In der input-Datei ist:

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

Ausgabe:

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

Wo ist die matrix kommen?

InformationsquelleAutor Chan | 2010-12-04
Schreibe einen Kommentar