Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ofstream writes \r even in binary mode

I am trying to write a UTF-16 encoded file using std::ofstream(). Even in binary mode writing "\n\0" is written as "\r\n\0". Sample code:

std::string filename = ...
std::ofstream fout(filename, std::ios_base::binary);
fout.write("\xff\xfe", 2);
fout.write("\n\0", 2);
fout.close();

The resulting file's hex data is:

ff fe 0d 0a 00

I must be doing something wrong. Any ideas to prevent the 0x0d being written?

I am using MS VisualStudio 2013.

Update: It inexplicably started working as expected. Chalk it up to ghosts in the machine.

like image 487
Jason Avatar asked Sep 01 '15 20:09

Jason


1 Answers

You sent 4 bytes to be output. 5 were observed in the output.

You were somehow not using binary mode. There is no other way you could use .write(buf, 2) and .write(buf, 2) and get 5 bytes of output.

Likely, in messing/playing around with things, (as people always do when trying to figure out why odd behavior) something you changed caused it to actually assert binary mode.

If you were earlier attempting to output to either STDOUT or STDERR, it's entirely possible that windows was automatically adding the '\r' into the stream because STDOUT and STDERR are almost always text, and this could have been overriding your attempt to put it into binary mode. (No, really. No, you're using Visual Studio, this is a really. Yes, if you use cygwin this isn't true, but you're using VS.)

like image 165
Cassy Foesch Avatar answered Oct 01 '22 18:10

Cassy Foesch