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

For some reason, this sorting code does not work 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 comes with Visual Studio 2010.

+4
source share
2 answers

The << operator is entirely to write formatted data to the stream. If you want to write binary data, you must use ostream::write() or ostream::put() .

+6
source

You need to first output the values ​​first as char , otherwise the iostream library will see the values ​​as int and format them as a readable string.

 theFile << (char)1 << (char)25; 
0
source

Source: https://habr.com/ru/post/1383171/


All Articles