Binary File example

Could someone send me a short example of reading an integer from a binary file? I can't seem to accomplish this.
Thanks for your help.
Sure. but keep in mind that raw binary I/O is non-portable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <fstream>
#include <iostream>
int main()
{
    int n = 42;

    // write to file
    {
        std::ofstream fout("test.bin", std::ios::binary);
        fout.write(reinterpret_cast<char*>(&n), sizeof n);
        std::cout << "value written: " << n << '\n';
    }

    // read from file
    {
        std::ifstream fin("test.bin", std::ios::binary);
        int m;
        fin.read(reinterpret_cast<char*>(&m), sizeof m);
        std::cout << "value read back: " << m << '\n';
    }
}
@Cubbi
Thanks, what does non-portable mean?
It means if you take that file to another computer (e.g. send over the network), reading it there may not give the same value. In case of a simple int, this would be true if
1) the computers have different endianness (e.g. PC vs. IBM)
2) the compilers have different size of int (e.g. 32-bit vs 16-bit if you can find one)
Last edited on
Topic archived. No new replies allowed.