9

I am trying to write binary file using std::ofstream::write method. I found out, that some characters are not written as they are, for example:

std::ofstream in("testout");
int i =10;

in.write((const char *)(&i), sizeof(i));
in.close();

return 0;

will write the following into a binary file: 0d 0a 00 00 00 Why is there additional 0d byte appearing?

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
coffee
  • 703
  • 2
  • 9
  • 14

3 Answers3

17

You´ll have to specify std::ofstream::binary when opening.

Else, on Windows in textfile mode, \n (0x0a) in a program will be converted to/from \r\n (0x0d 0x0a) when writing/reading the file.

P0W
  • 46,614
  • 9
  • 72
  • 119
deviantfan
  • 11,268
  • 3
  • 32
  • 49
  • 1
    @MarkGarcia no poems here on SO ;) – P0W Feb 24 '14 at 08:59
  • Good that it is preserved in the edit section for eternity :p But to think of a haiku when reading answer here...that alone is remarkable enough :) – deviantfan Feb 24 '14 at 09:02
  • 1
    You might add that binary mode alone isn't sufficient to ensure that he can reread the file. You can't just dump memory images to disk and expect to reread them later. (The fact that he needs a `reinterpret_cast` to do this should be a good indication that it won't work.) – James Kanze Feb 24 '14 at 09:20
6

You opened the file in text mode and running on Windows. It adds the 0x0d to 0x0a. You need to use binary mode when you create the ofstream instance.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
littleadv
  • 20,100
  • 2
  • 36
  • 50
4

The file is being written on a system that does text to binary translation. The value 10 (0A hex) in the lowest byte of i is being interpreted as a linefeed character (aka newline), and is being converted to a carriage return linefeed sequence (13 10 decimal, 0D 0A hex).

To solve this issue, change the first line of your code snippet as follows:

std::ofstream in("testout", std::ios::binary);

This will instruct the C++ runtime library to treat the file as binary and not perform any translation of bytes between newline and carriage return linefeed sequences.

CasaDeRobison
  • 377
  • 2
  • 12