I have the following code below in C++ to write a binary file. It outputs the file but when I open it. I see it is an ASCII format. What am I doing wrong ? How do I get the string message to be saved as binary into the file ?
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using std::ios;
void writeFile(const std::string &fileName, const std::string data)
{
std::ofstream ofs;
ofs.open(fileName.c_str(), ios::out | ios::binary);
if ( ofs.is_open())
{
ofs.write(data.c_str(),data.size());
ofs.close();
}
else
{
std::cerr <<"Error while writing File: "<<fileName<<std::endl;
exit (EXIT_FAILURE);
}
}
int main(int argc, char const *argv[])
{
/* code */
std::string message = "This should be binary";
writeFile("sample", message);
return 0;
}
If your string is ASCII text, and you're opening in binary mode, the file is going to be filled with ASCII text; ASCII has a 1-1 correspondence between characters and bytes, so a text editor interpreting the contents as ASCII will see it as text.
Binary mode typically only matters on Windows, where it disables line ending conversions. On Windows in text mode, \n
in a string is converted to \r\n
seamlessly on output, and from \r\n
to \n
on input to match Windows conventions. Binary mode disables that transformation, but otherwise changes nothing.
If you want to confirm this on Windows, write a string like "Foo\nBar"
to a file in binary mode, then open it with notepad.exe
(it's a "dumb" editor that insists on \r\n
only for line endings). It will show both words on a single line; if you wrote the same string to file in text mode, they'd appear on different lines.