How to create a binary file with write()

Feb 13, 2012 at 3:39pm
I want to create a binary file. But when i input string "hello world!" for the file, the following code cann't create a binary file, it create a text(ASCII) file, why? Or the string must be converted to hex numbers for a binary file?

Development enviroment: Microsoft Visual Studio 2008.

#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
char strdata[100];
fstream hfile;
hfile.open("output", ios::binary|ios::in|ios::app|ios::out);
if(hfile.is_open())
{
cin.getline(strdata, 100);
hfile.seekg(ios_base::end);
hfile.write(strdata, strlen(strdata));
}
hfile.close();
}
Last edited on Feb 13, 2012 at 5:27pm
Feb 13, 2012 at 3:56pm
If you write 'ios::in' the fstream expects that the file exists. If not it cannot be opened.

So remove ios::in and it should work
Feb 13, 2012 at 5:25pm
Thanks! But the code can work. But the content of the file is text(ASCII) file, not binary file.
Feb 13, 2012 at 6:48pm
What exactly do you mean by a binary file?
Why do you think you are not creating a binary file?

From your description and code, it looks like you are creating a binary file which should be 12 bytes in size. If you opened your "output" file in wordpad, I would expect to see "hello world!".

The only differences between binary files and text files are that text files may perform special processing on end-of-line and end-of-file characters (classic behavior is to combine carraige returns and linefeeds into a single newline, or to treat control-Z as the end of file).

If you want to see something like "104 101 108 108 111 32 ...", where 104 is the decimal code for the letter 'h', you do not want a "binary file", you want to do a conversion. Try converting each character individual into a decimal value and print those values to the screen first. Once you get that done, then try writing them to a file.

Topic archived. No new replies allowed.