[英]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. 我正在尝试通过ppm文件进行解析,但首先需要验证标题信息是否正确。 A ppm file may have the following formats:
ppm文件可能具有以下格式:
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);
我正在使用
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. 我想知道的是,如何在移动到读取数据(
char
由char
验证头信息后)。
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. 假设标头告诉您数据的大小,然后分配一个足够大的内存块,并使用fread()在一次调用中读取它-比一次读取一个字节要快得多。
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"
. 使用
fscanf
可以读取带有"%c"
的字符。
char ch;
while (fscanf(file_stream, "%c", &ch) == 1) {
/* process ch */
}
But instead of fscanf
you can use fgetc()
但是可以使用
fgetc()
代替fscanf
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. 但是,假设使用ASCII编码(P1,P2或P3)的ppm文件,
fscanf
是一个非常好的选择。
/* 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 如果要处理二进制PPM,请记住以二进制模式打开文件
fopen(filename, "rb");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.