Question

I am writing to binary file using fstream and when open the file using binary flag.

I needed to write some text as binary, which a simple write did the trick. The problem is that I need also to write (as shown in hexadecimal) 0. The value when opened in binary notepad is shown zero, but when tried to write this the value not zero it was value of 30 in hexadecimal.

How you write specific data like this?

Was it helpful?

Solution

When you open the fstream use the ios::binary flag to specify binary output. More information can be found here.

As for writing 0, when you see 30 in hexidecimal you are writing the character '0', not the binary number 0. To do that with an fstream you can do something like:

my_fstream << 0;

Keep in mind the binary data 0 has no textual representation, so you will not be able to read it in Notepad like you would be able to read the character '0'.

OTHER TIPS

You probably just need something like this, improve as you see fit:

ofstream file("output.bin", ios::out | ios::binary);
if (file.good())
{
    char buf[1] = {0};
    file.write(buf, sizeof(buf));
    file.close();
}

Links to more sophisticated solutions and documentation were already posted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top