Help With Reading The Image Size Of A PPM File?
I've used this code before to test it and it did work. Unfortunately it now reads two random numbers for a pgm file and the code ends before it even gets to read the image dimensions when I try to read a ppm file in. I know I'm missing something but I'm not quite sure where yet. Any help is much appreciated. Thanks. (the code is also unfinished)
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()
{
FILE *fp;
PPMImage *img;
int d;
char buff[16];
char fname[100];
printf("Enter file name: ");
scanf("%s", fname);
fseek(stdin,0,SEEK_END);
fp = fopen(fname, "rb");
if (fp == NULL || !fp || ferror(fp))
{
printf("\tError while opening the file\n");
}
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");
}
//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);
}
}
void save_file(PPMImage *img)
{
}
int main()
{
char key = 0;
PPMImage* img = NULL;
do {
puts("\tPress r to read in an image in ppm format");
puts("\tPress s to save image in ppm format");
puts("\tPress q to quit");
scanf(" %c", &key);
clear_to_end(stdin);
switch (key) {
case 'r':
// TODO: if img != NULL, free it
img = load_file();
break;
case 's':
save_file(img);
break;
case 'q':
puts("\tTerminating program...");
break;
default:
puts("\tInvalid Input");
break;
}
} while (key != 'q');
return0;