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

2

6

I'm working with a basic std::ofstream object, created as follows:

output_stream = std::ofstream(output_file.c_str());

This creates a file, where some information is put in. Let me show an example of such a message: (Watch window excerpt)

full_Message    "Error while processing message:\r\n\tForecast Request:"

All this is ok, but after having launched following commands, there is a problem:

output_stream << full_Message;
output_stream.flush();

In order to see what is wrong, let's look at the hexadecimal dump of the file: (this is a hexadecimal display of the file, as seen in Notepad++. For clarity reasons I've taken a screenshot.)

Notepad++ Hexdump screenshot

As you can see, the character 0d is doubled, resulting in following display:

Error while processing message:

    Forecast Request:

(There's a newline too much, both lines should be directly one after the other)

I am aware of the addition of #13 characters while doing file conversion from UNIX/Linux to Windows, but this is not relevant here: I'm purely working with a Windows file, on a Windows system, so there should be no need to add any #13 character.

Does anybody have an idea how I can avoid this extra character being added?

Thanks in advance

Hb answered 21/3, 2018 at 11:22 Comment(2)
Probably related. Or this, this, this.Tasty
Possible duplicate of Why does ofstream insert a 0x0D byte before 0x0A?Sundown
L
16

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);
Lattimer answered 21/3, 2018 at 11:24 Comment(1)
I had just this problem, thanks for the tip. Now I have new, UTF-8 problems. Text is fun...Burgwell
F
4

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'.

Frechette answered 21/3, 2018 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.