简体   繁体   中英

Reading ppm files and using fscanf()

I'm trying to parse through a ppm file, but first need to verify if the header info is 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);

%*[\\n]添加到fscanf字符串的末尾以吃掉标题中的最后一个换行符,然后可以使用fread从文件的其余部分读取原始字节(假定您以二进制模式打开它)。

是否有某些原因不使用netpbm库?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM