This works on Windows and on Solaris (Unix):
Code:
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
Expect a series of images of the form base0000.ppm, base0001.ppm, etc
Supports forward or reverse image ordering
*/
int main(int argc, char **argv) {
unsigned char *ptr_data;
int i=0, height, width, color;
FILE *temp_fptr;
size_t totBytes, bytesRead;
const char *fileName = "img0061.ppm"; /* get from the command line */
char buf[BUFSIZ];
temp_fptr = fopen(fileName,"rb");
if (!temp_fptr){
fprintf(stderr, "Can't open file!\n");
exit(1);
}
/* get and check magic number */
i=0;
while (!isspace(buf[i] = fgetc(temp_fptr))){i++;}
buf[i] = '\0';
if (strncmp(buf, "P6", 2)){
fprintf(stderr, "File's magic number is invalid! (only read P6 files)\n");
exit(1);
}
/* get and check width */
i=0;
while (!isspace(buf[i] = fgetc(temp_fptr))){i++;}
buf[i] = '\0';
if (sscanf(buf, "%d", &width) != 1){
fprintf(stderr, "Failed to read in width correctly!\n");
exit(1);
}
if (width < 1 || width > 65536){ /* arbitrary upper limit, you can change this */
fprintf(stderr, "Invalid or out-of-bounds value for width!\n");
exit(1);
}
/* get and check height */
i=0;
while (!isspace(buf[i] = fgetc(temp_fptr))){i++;}
buf[i] = '\0';
if (sscanf(buf, "%d", &height) != 1){
fprintf(stderr, "Failed to read in height correctly!\n");
exit(1);
}
if (height < 1 || height > 65536){ /* arbitrary upper limit, you can change this */
fprintf(stderr, "Invalid or out-of-bounds value for height!\n");
exit(1);
}
/* get color (don't care about validity) */
i=0;
while (!isspace(buf[i] = fgetc(temp_fptr))){i++;}
buf[i] = '\0';
if (sscanf(buf, "%d", &color) != 1){
fprintf(stderr, "Failed to read in color correctly!\n");
exit(1);
}
totBytes = 3*width*height;
ptr_data = (unsigned char *) malloc(totBytes);
if (!ptr_data){
fprintf(stderr, "Failed to allocate %d bytes of memory!\n", totBytes);
exit(1);
}
bytesRead = fread(ptr_data, 1, (totBytes), temp_fptr);
printf("\nbytesRead: %d\nFirst 10 bytes in hex:\n", bytesRead);
for (i=0; i<10; i++){
printf("%02X ", ptr_data[i]);
}
printf("\n");
fclose(temp_fptr);
free(ptr_data);
return 0;
}
My output:
bytesRead: 1045008
First 10 bytes in hex:
70 38 29 6A 3B 2A 59 31 27 51