Why does std::ofstream add extra #13 (newline) characters?

[亡魂溺海] 提交于 2019-12-01 12:07:49

The streams default to text mode, which means that in Windows, if you write \n then the file gets \r\n. Therefore , if you write \r\n then the file gets \r\r\n.

To fix this, either just write \n in your code; or open the file in binary mode:

auto output_stream = std::ofstream(output_file.c_str(), std::ios::binary);

Because by default the library converts '\n' to "\r\n" for text streams on platforms where it's needed (like Windows).

So you don't need your explicit carriage-return in your string. It's handled automatically.

If you want to specify the carriage-return explicitly, then you need to open the file in binary mode.


When reading a text stream, the opposite conversion happens, with "\r\n" being converted to '\n'.

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