Reading ppm files and using fscanf()
I'm trying to parse through a ppm file, but first need to verify if the header info i开发者_如何转开发s correct. A ppm file may have the following formats:
P3
100 100
255
data...
or
p3
100 100
255
data...
I'm using fscanf (file_stream, "P3 %d %d %d", &width, &height, &max_colour);
to verify the header info. What I'd like to know is, how to move on to reading the data (char
by char
) after verifying the header info.
Assuming the header tells you the size of the data then allocate a block of memory that is large enough and use fread() to read it in a single call - this is MUCH faster than reading a byte at a time.
unsigned char *data = malloc(width*height); // or whaterver size
fread(file_stream,width*height,1,data);
Add a %*[\n]
to the end of your fscanf
string to eat the last newline in the header, then you can use fread
to read raw bytes from the remainder of the file (assuming you opened it in binary mode).
Is there some reason not to use the netpbm library?
Using fscanf
you can read a char with "%c"
.
char ch;
while (fscanf(file_stream, "%c", &ch) == 1) {
/* process ch */
}
But instead of fscanf
you can use fgetc()
int ch;
while ((ch = fgetc(file_stream)) != EOF) {
/* process ch */
}
But, assuming a ppm file with ASCII encoding (P1, P2, or P3), fscanf
is a really good option.
/* P3 format */
if (fscanf(file_stream, "%d%d%d", &red, &green, &blue) == 3) {
/* RGB triplet read; process it */
}
Remember to open your file in binary mode if you want to deal with binary PPMs
fopen(filename, "rb");
精彩评论