I used
std::cout << (char)0xA
in my C++ code.
Then, I wrote to the console myProgram.exe > file.txt
.
Next, I opened file.txt
with A HEX editor and I found 0D 0A
instead of 0A
.
IDK why this happened. Please, help.
I used
std::cout << (char)0xA
in my C++ code.
Then, I wrote to the console myProgram.exe > file.txt
.
Next, I opened file.txt
with A HEX editor and I found 0D 0A
instead of 0A
.
IDK why this happened. Please, help.
The C and C++ Standards both specify that when a stream is open in text mode, sending a \n
to it will do whatever action is necessary on the target system to advance the file to the next line. On a Unix system, that simply means outputting a \n
to a file. On some record-based systems, it means flushing the current line-output record and advancing to the next one. On MS-DOS and Windows, it means sending both a \r
and \n
to the stream.
Historically, sending a \r
to a teletype would reset the carriage to the left edge, and sending a \n
would advance the paper. Someone realized that while the ability to reset the carriage without advancing paper was useful, having \n
advance the paper without resetting the carriage was far less so, and thus some devices will respond to \n
by advancing to the start of the next line. MS-DOS, however, opted to have files stored in a way that would produce meaningful output if sent directly to a printer where \n
would advance to the current location on the next line, and one would have to send both \r
and \n
if one wanted to go to the start of the next line.
Welcome to the magic of end of lines across OS!
The C language originally was developped for Unix systems where the end of line was marked by the single '\n'
(ASCII code 0x0A
) character.
When it was ported to other systems, it was decided that seen from the programmer an end of line will only be a '\n'
, and that the drivers and the standard library would convert it to the appropriate line ending when the file would be opened in text mode.
That convention was later keeped in C++.
As Windows uses "\r\n"
as an end of line marker, the standard library convert any '\n'
to the pair "\r\n"
(ASCII codes 0x0D
and 0x0A
).