简体   繁体   中英

How to use fscanf to parse a binary file

I am trying to use fscanf to parse a binary file (an image).

Here is the beginning of the file. I want to get the 'width' and 'height' of the file. In this case, width is 640, height is 480

00000000: 5036 0a23 2043 7265 6174 6564 2062 7920  P6.# Created by 
00000010: 4972 6661 6e56 6965 770a 3634 3020 3438  IrfanView.640 48
00000020: 300a 3235 350a a079 35a0 7833 a179 349f  0.255..y5.x3.y4.

So the header is 'P'some characters followed by 0xa (line feed) followed by width followed by space (0x20) and followed by height'

In my code, I have

  t=fscanf(fin,"P%c\r%d %d",&fc,&w, &h);
  or 
  t=fscanf(fin,"P%c\n%d %d",&fc,&w, &h);

But t always returns 1 (instead of 3) and my w and h is not read.

Can you please tell me how can I fix my problem?

You need to skip the text "# Created by...\\n". So try:

t=fscanf(fin,"P%c\n%*[^\n] %d %d", &fc, &w, &h);

You can achieve this by simply reading aways the first 26 characters and then saving the width and height in integer variables

char fc[26];
val=fscanf(fp,"%26c %d %d",fc,&w,&h );

"26" is the width which specify the maximum number of character to be read in the current operation. So this will read away the first 26 characters whatever they may be and save you much trouble in reading the width and height, which is actually what you want.

Be careful in using "fc" as a string. No "NULL" character is added at the end. "fc" is just a array of character and is not NULL terminated.

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