1

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?

3
  • Post some code if you please, so we can get a better understanding of what you're doing. Commented Sep 9, 2009 at 17:36
  • Do you use write or << ? Commented Sep 9, 2009 at 17:48
  • Serialization is common term for this. Commented Sep 9, 2009 at 17:53

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it did the trick. Can u please explain the difference between writing char c = "0"; and char c = {0}; ?
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: cplusplus.com/doc/tutorial/arrays and here: cplusplus.com/doc/tutorial/ntcs
1

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

2 Comments

You probably meant: my_fstream << '\0';
Can u please explain the difference between writing char c = "0"; and char c = {0}; ?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.