Windows C++ | When writing to file, what is responsible for converting \n to \r\n?

Viewed 119

When writing to file, strings with \n get automatically converted to \r\n.

What is responsible for this behaviour? Is this a part of the cpp function, or something closer to the system?

1 Answers

It's your compiler.

When you are working with OS-specific outputs (like files or standard output), compiler is obliged to convert end-of-line escape sequence (\n) to OS-specific line ending - on Unix it would be a line feed (ASCII 0x0A), on older Macs it's a carriage return (ASCII 0x0D) and on Windows it's both.

You can avoid that by opening file in binary mode:

std::fstream("myFile.txt", std::ios_base::binary);
Related