#include "imglib.h" #define PPMREADBUFLEN 256 image get_ppm(FILE *pf) { char buf[PPMREADBUFLEN], *t; image img; unsigned int w, h, d; int r; if (pf == NULL) return NULL; t = fgets(buf, PPMREADBUFLEN, pf); /* the code fails if the white space following "P6" is not '\n' */ if ( (t == NULL) || ( strncmp(buf, "P6\n", 3) != 0 ) ) return NULL; do { /* Px formats can have # comments after first line */ t = fgets(buf, PPMREADBUFLEN, pf); if ( t == NULL ) return NULL; } while ( strncmp(buf, "#", 1) == 0 ); r = sscanf(buf, "%u %u", &w, &h); if ( r < 2 ) return NULL; r = fscanf(pf, "%u", &d); if ( (r < 1) || ( d != 255 ) ) return NULL; fseek(pf, 1, SEEK_CUR); /* skip one byte, should be whitespace */ img = alloc_img(w, h); if ( img != NULL ) { size_t rd = fread(img->buf, sizeof(pixel), w*h, pf); if ( rd < w*h ) { free_img(img); return NULL; } return img; } }