Search code examples
cc89

Reading a grid from a text file and storing it within a two-dimensional array?


Suppose you had a file called "input.txt" that looked like this:

5
0 0 0 0 0 
0 0 0 0 0 
0 1 1 1 0 
0 0 0 0 0 
0 0 0 0 0 

A 5 x 5 grid above. And you wanted to store the 5 x 5 grid into a two-dimensional C array. My issue is reading the file into that grid.

This is my C file that reads in the data, stores it in a 2D integer array and outputs its contents

int main (int argc){

    FILE *fp;
    char ch;
    int **C; //Our 2D Array
    char filenamein[] = "input.txt";

    fp = fopen(filenamein,"r"); 

    N = (ch = fgetc(fp)) - 48; 

    //Initialize Grid, set all cells to 0
    C = malloc(N * sizeof(int *));
      for (i = 0; i < N; i++) {
             C[i] = malloc(N * sizeof(int));
      }
    for (i=0;i<N;i++) {
     for (j=0;j<N;j++) {
       C[i][j]=0;
     }
    }

   //Read array, store into array
    while ((ch = fgetc(fp) ) != EOF)
    {
    for (i=0;i<N;i++){
        for (j=0;j<N;j++){
        C[i][j] = ch - 48;
        }
    }
    }

    //Print 2D Array:

     for (i = 0; i < N; i++) {
             for (j = 0; j < N; j++)
               printf("%d ", C[i][j]);
             printf("\n");
           }

fclose(fp);
}

Upon calling this I get:

-38 -38 -38 -38 -38
-38 -38 -38 -38 -38
-38 -38 -38 -38 -38
-38 -38 -38 -38 -38
-38 -38 -38 -38 -38

The grid outputs the char-to-decimal ASCII code for Whitespace/NULL from what I deducted so my issue is reading in the text file into the array.

How can I read the text file to store the numbers into the array?


Solution

  • This code work as expected. it's better to use fscanf instead of fgetc but I did not correct this in your code.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main (int argc, char *argv[])
    {
        FILE *fp;
        unsigned char ch;
        int **C; //Our 2D Array
        int N, i, j;
        char filenamein[] = "input.txt";
    
        fp = fopen(filenamein,"r");
    
        N = (ch = fgetc(fp)) - 48;
    
        //Initialize Grid, set all cells to 0
        C = malloc(N * sizeof(int *));
        for (i = 0; i < N; i++)
            C[i] = malloc(N * sizeof(int));
    
        for (i = 0; i < N; i++)
            for (j = 0; j < N; j++)
                C[i][j] = 0;
    
        i = 0;
        j = 0;
        do {
            ch = fgetc(fp);
            if (ch != ' ' && ch != '\n') {
                C[i][j] = ch - 48;
                j++;
                i += j / N;
                j %= N;
            }
        } while(i < N && j < N);
    
        //Print 2D Array:
        for (i = 0; i < N; i++) {
            for (j = 0; j < N; j++)
                printf("%d ", C[i][j]);
            printf("\n");
        }
        fclose(fp);
    }