1

I have this binary file with showing the correct value when I opened the file using HexView.

4c 60 02 aa b4 c2 d1 e3 1a 01 00 00 8c 01 00 00 f5 01 00 00 52 02 00 00 bd 02 00 00 20 03 00 00 32 03 00 00 59 03 00 00

When I uses fread to read the 40 bytes data into a char buffer, it failed. From 9th byte data onwards, all the read back data is 0x00.

int main()
{
    FILE *stream;
    char flag[40]={0};
    size_t numread = 0;
    UINT theme = 0;

    if ((stream = fopen("alignment.bin", "r")) != NULL)
    {
        numread = fread(&flag, 1, 40, stream);

        fclose(stream);
    }
    else
    {
        cout << "File open failed" << endl;
    }
    system ("pause");
    return 0;
}
3
  • 2
    Are you using Windows by any chance? The 9th byte is 1a (a.k.a Ctrl+Z) which may be considered an end-of-file in Windows.
    – Ray Toal
    Sep 12, 2011 at 2:56
  • Yes, is in Windows environment. Any idea what is the meaning of Ascii 0x1a?
    – okwoei
    Sep 12, 2011 at 3:12
  • it means end-of-file for Windows text files. I had that in my answer but I deleted the after realizing that Mystical was first with the "rb" by a couple minutes! See en.wikipedia.org/wiki/Control-Z
    – Ray Toal
    Sep 12, 2011 at 3:30

2 Answers 2

9

Try using "rb" instead of "r". There might be some weird text formatting issues.

Specifying the b makes it read in pure binary with no formatting.

2
  • So, by using "rb", it will make the reading purely in binary, ignoring those special character in Ascii map?
    – okwoei
    Sep 12, 2011 at 3:16
  • The special bytes will not be "ignored", but no action taken on them. Jan 9, 2012 at 16:05
0

0x1A == 26 == ctrl-Z == EOF.

If you read in text mode, the stream consider the flow finished after that point (what follow is "rubbish for other transmissions").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.