Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing binary to std::fstream using the << operator

Tags:

c++

For some reason this sort code is not working as I would expect:

std::fstream theFile;
theFile.open(<someFilename>, std::ios::beg |std::ios::out|std::ios::binary|std::ios::trunc);
theFile << 1;          //1 is being written as a string
int var= 25;

theFile << 25;        //same thing, 25 is written as a string

What could be the problem? I am using the Microsoft C++ compiler that ships with Visual Studio 2010.

like image 420
seggaeman Avatar asked Nov 26 '11 09:11

seggaeman


1 Answers

The << operator's whole purpose is to write formatted data to a stream. If you want to write binary data, you should use ostream::write() or ostream::put().

like image 176
fschoenm Avatar answered Sep 27 '22 22:09

fschoenm