Reputation: 14997
I'm used to using fwrite to write the contents of a buffer to a file in gcc. However, for some reason, fwrite doesn't seem to work correctly in Visual C++ 2005.
What I'm doing now is to convert a text file into binary. The program worked fine for the first 61 lines, but at the 62nd line, it inserted a 0x0d into the output binary file. Basically, it turned the original
12 0a 00
to
12 0d 0a 00
I checked the buffer, the content was correct, i.e.
buffer[18] = 0x12, buffer[19] = 0x0a, buffer[20] = 0x00
And I tried to write this buffer to file by
fwrite(buffer, 1, length, fout)
where length is the correct value of the size of the buffer content.
This happened to me once, and I had to change my code from fwrite to WriteFile for it to work correctly. Is there a reason a 0x0d is inserted into my output? Can I fix this, or do I have to try using WriteFile instead?
Upvotes: 0
Views: 211
Reputation: 26279
The problem is because the file has been opened in text mode, so it is converting each of the newline characters it sees to a newline+carriage return sequence.
When you open your file, specify binary mode by using the b qualifier on the file mode:
FILE *pFile = fopen(szFilename, "wb");
In VC++, if t or b is not given in the file mode, the default translation mode is defined by the global variable _fmode
. This may explain the difference between compilers.
You'll need to do the same when reading a binary file too. In text mode, carriage return–linefeed combinations are translated into single linefeeds on input, and linefeed characters are translated to carriage return–linefeed combinations on output.
Upvotes: 2