0

I am trying to read in a P2 PGM image into a 2D array in C.

The array is 5 rows and 7 columns. When i try to read in the values from the .PGM file all i get are 0s. When i create my own .txt file with the same 5 rows and 7 columns as the image it works perfectly. So i think the problem is the P2 header.

int main() {

int aarray [5] [7] = {0};
int cols = 7;
int rows = 5;
int i;
int j;

FILE *input_fptr;

input_fptr = fopen("image1.pgm", "r");

if (input_fptr!=NULL)
{
    for (i=0; i<rows; i++)
    {
        for (j=0; j<cols; j++)
        {
            fscanf(input_fptr, "%d", &aarray[i][j]);
            printf("%d\n", aarray[i][j]);
        }
    }
}
fclose(input_fptr);
return 0;
}

Is there a way of skipping these first 3 lines then reading in the values into the array?

Paulo Tomé
  • 1,910
  • 3
  • 18
  • 27
mitch
  • 1
  • Use `fgets` to read and discard however many number of lines you don't want to process. – kaylum Nov 24 '19 at 21:35
  • Read characters from file until 3 newlines are encountered? What have you tried? – KamilCuk Nov 24 '19 at 21:37
  • i have seen other solutions to similar problems that involved strings and characters, that has me confused as i thought this would only involve integers? – mitch Nov 24 '19 at 21:46
  • the P2 header can indeed have strings, and even comments – B. Go Nov 24 '19 at 22:11

0 Answers0