writing integers, doubles etc directly into a binary file

Jun 1, 2010 at 4:15pm
Hello everyone!
I (not the biggest c++ professional) spent some hours today trying to solve this problem:

I need to create a binary file and want to be able to write integers/doubles etc. directly into it. Since i am not very good at c++ i don't know what to do best.


The file begins with a 256 Bytes long header that i need to fill up.

0-7th Byte will be filled with zeros.
8-55th Byte should contain 6 doubles
...
61-191th Byte should contain 16 doubles.
etc.

First of all, i don't really know how to write a binary from stream.
I used
stream.open("path/test.txt", ios::binary) to later write in a binary format.

Now how do I put the contents of double variables into the file so that exactly 4 Bytes will be reserved and filled with the variable's content?

I tried to check what i did by opening the file in a hex-viewer. What I did so far did not show the results i was looking for:

In the hex-viewer the file should begin with

00 00 00 00 00 00 00 00 (0-7th Byte: Zeroes).

When i wrote into the empty binary file in this way though, i got other hex numbers than zeroes in the beginning.

1
2
3
4
5
6
ofstream stream;
stream.open("path", ios::binary);

double k = 0;
stream << k;
stream.close();



I am sorry I do not know how to put the problem best. Another way of asking for your help would be: How do I write a binary File that looks like this picture (http://www.avl-web.de/Geoheader.png) after opening it with a hex-viewer?

Many thanks for any help!
Jun 1, 2010 at 4:26pm
Use write():

stream.write(reinterpret_cast<char*>(&k),sizeof(k));
Jun 1, 2010 at 5:18pm
how do i put the contents of double variables in there? is that information included in the expression in the brakets? how do i interpret it?
Jun 1, 2010 at 5:57pm
k is your double. I used k because you did.

For the write documentation, see
http://www.cplusplus.com/reference/iostream/ostream/write/

reinterpret_cast<char*>(&k) will give you the starting address of your double as a char* pointer (because unfortunately, that's what write expects). sizeof(k) will give you the size of a double. So this will sizeof k bytes of your double, or in other words, it will write your double value.
Jun 2, 2010 at 2:23am
Simply casting does not account for endianness issues.
If it makes a difference (and it should), check out the little_endian_io and big_endian_io namespaces and functions I made here:
http://www.cplusplus.com/forum/beginner/11431/#msg53963

Hope this helps.

[edit] This post is not necessarily useful to you... Also, there is no platform-agnostic way of writing floating-point values to file in binary mode... In their case, text-formatted values are the usual way to fix it...
Last edited on Jun 2, 2010 at 2:25am
Topic archived. No new replies allowed.