std::ofstream::write adds characters

后端 未结 3 1520
执笔经年
执笔经年 2020-12-30 10:20

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:

         


        
3条回答
  •  庸人自扰
    2020-12-30 10:39

    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.

提交回复
热议问题