views:

237

answers:

3

Hello,

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 ?

Thnaks

+1  A: 

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'.

fbrereto
He did that already.
Mark P Neyer
Yes, the text is bad, but the link is good.
gimpf
You probably meant: my_fstream << '\0';
sbk
Can u please explain the difference between writing char c = "0"; and char c = {0}; ?
Roman Dorevich
+1  A: 

Take a look at this: http://www.cplusplus.com/forum/general/11272/

A: 

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.

Dmitry
Thanks it did the trick.Can u please explain the difference between writing char c = "0"; and char c = {0};?
Roman Dorevich
NP. When you're writing a "0" you're writing a _string_ with a zero-character with a value equal to it's ASCII code 0x30h, and that's why when opened in notepad you saw it as a zero character and 0x30 in your hex viewer. {0} essentially equals to filling an array with zeroes, and you were no longer writing a 0x30h, but a true 0x00h that you were looking for. Good explanation of the difference you can find in here: http://www.cplusplus.com/doc/tutorial/arrays/ and here: http://www.cplusplus.com/doc/tutorial/ntcs/
Dmitry