19

I have a very simple question, which happens to be hard for me since this is the first time I tried working with binary files, and I don't quite understand them. All I want to do is write an integer to a binary file.

Here is how I did it:

#include <fstream>
using namespace std;
int main () {
    int num=162;
    ofstream file ("file.bin", ios::binary);
    file.write ((char *)&num, sizeof(num));
    file.close (); 
    return 0;
}

Could you please tell me if I did something wrong, and what?

The part that is giving me trouble is line with file.write, I don't understand it.

Thank you in advance.

9

1 Answer 1

38

The part that is giving me trouble is line with file.write, I don't understand it.

If you read the documentation of ofstream.write() method, you'll see that it requests two arguments:

  1. a pointer to a block of data with the content to be written;

  2. an integer value representing the size, in bytes, of this block.

This statement just gives these two pieces of information to ofstream.write():

file.write(reinterpret_cast<const char *>(&num), sizeof(num));

&num is the address of the block of data (in this case just an integer variable), sizeof(num) is the size of this block (e.g. 4 bytes on 32-bit platforms).

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

3 Comments

Important notice here: it writes data from the memory as it is stored there and resulting binary file will be not readable on machines with different endianness.
@Mikolasan how can i make it so that the binary file is readable on different machines?
@thatGuy your code should check what endianness on the running machine, if it differs from binary file format, then convert the data after reading or before writing, otherwise read/write and use as it is.

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.