简体   繁体   中英

parsing a binary file in C

I am trying to read a binary file for it's content It has two sets of lines for each component Second last character on the first line indicates the type of the component file ( ^A for assembly and ^B for part) If the type is ^A I need to parse the file specified in next line which starts with name^@

àtype^@^Aà
name^@assembly1

àtype^@^Aà
name^@assembly2

àtype^@^Bà
name^@apart1

àtype^@^Bà
name^@apart2

When I try to parse this file, I can not read past the binary characters in the file. First line contains a binary character ( à ) so I get an empty line. Second line has ^@ after name, so I only get 'name' and the len is 4. This is my code snippet

FILE *fp;
  char line[256];
  fp = fopen(name, "rb");
  fgets(line, 256, fp);

  printf("line %s\n", line);
  printf("len %d\n\n", strlen(line));

  fgets(line, 256, fp);

  printf("line %s\n", line);
  printf("len %d\n\n", strlen(line));

This is the output

line 
len 0

line name
len 4

My aim is to parse the type of component (^A or ^B) and then get the name of the component. Please help in pointing out how to solve this.

fgets and most <stdio.h> functions work with text , not binary data.

The "character" ^@ has, I think, the binary value 0 , which messes up all the string handling functions.

You need to read character-by-character and/or not use string functions with objects containing embedded zero bytes.

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