0

I'm trying to write some value to a file byte by byte while when it comes to the value of 10, it write 0D0A instead of only 0A ot the file, any idea?

unsigned char m = 10;
ofstream fout("1.file");
fout << m;
fout.close();

output of the file

Joe
  • 3
  • 6

1 Answers1

2

I'm guessing you're on a Windows system, where newlines ('\n', ASCII value 10) are automatically translated to the Windows newline "\r\n" (ASCII values 13 and 10).

This translation happens for all files opened in text mode on Windows. And in the opposite direction when reading. Opening in binary mode will not do this translation.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Yes, I'm on windows system, but i didn't open it by any text editor but directly read the file by another program, and still cause this translation, is there any solutions to prevent it? Or how can I only write 0A to the file? – Joe Nov 14 '18 at 12:28
  • 2
    You could open the file in binary mode. See the `mode` parameter in the constructor of `ofstream`: https://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream – Yanick Salzmann Nov 14 '18 at 12:31
  • 1
    https://en.cppreference.com/w/cpp/io/c#Binary_and_text_modes expands on what Some programmer due explained. – Yanick Salzmann Nov 14 '18 at 12:34
  • Appreciate!! I'll check it out! – Joe Nov 14 '18 at 12:37