1

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.

1
  • What on earth is a "binary character"? What's a "non-binary character", for that matter? Commented Oct 10, 2011 at 18:57

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that fgets reads all the bytes, including the '\0' and the following ones -- but, again, you cannot use string functions on that data. After you read the second line, line[4] is 0 but printf("%s\n", line+5) outputs "assembly1".
Thanks pmg. Both the answer and this comment helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.