A few tweaks.
Code:
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#define RGB_COMPONENT_COLOUR 255
#define height 1080
#define width 1920
typedef struct
{
unsigned char red, green, blue;
} PPMPixel;
typedef struct
{
int x, y;
PPMPixel *data;
} PPMImage;
void clear_to_end(FILE *fp)
{
int c;
while ((c = fgetc(fp)) != -1 && c != '\n');
}
PPMImage* load_file(const char *fname)
{
FILE *fp;
PPMImage *img = malloc(sizeof(*img)); //!! allocate space!
int d;
// https://en.wikipedia.org/wiki/Netpbm#PPM_example
// according to this, max length of any line is 70 chars
char buff[80];
fp = fopen(fname, "r"); //!! not rb for text files!!
if (fp == NULL)
{
printf("\tError while opening the file\n");
return NULL;
}
else
{
printf("\tReading in %s\n", fname);
}
//Checking for comments
//Skip whitespace and comments
d = getc(fp);
while (d=='#')
{
while(getc(fp)!='\n')
d=getc(fp);
}
ungetc(d,fp);
//Checking header
if (!fgets(buff,sizeof(buff),fp))
{
perror(fname);
exit(1);
}
if (buff[0] =='P' && (buff[1] == '2' || buff[1] == '3'))
{
printf("\tReading PGM/PPM image in...\n");
}
else
{
printf("\tIncorrect image format\n");
return NULL;
}
//Read image size information
if (fscanf(fp, "%u%u", &img->y, &img->x))
{
printf("\tInvalid image size\n");
printf("\tImage size is: %u x %u\n", img->y, img->x);
}
else
{
printf("\tImage size is valid\n");
printf("\tImage size is: %u x %u\n", img->y, img->x);
}
return img;
}
int main()
{
PPMImage* img = load_file("foo.pbm");
free(img);
}
Results
Code:
$ gcc foo.c
$ head foo.pbm
P3
107 48
255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
$ ./a.out
Reading in foo.pbm
Reading PGM/PPM image in...
Invalid image size
Image size is: 107 x 48