std::ofstream::write adds characters

◇◆丶佛笑我妖孽 提交于 2019-11-30 09:37:45
deviantfan

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.

littleadv

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!