Writing/reading binary bytes/ints/longs to/from file stream in C++

317 views Asked by At

So I've only recently started to try C++ and I've already learned the basics. All I want to know is how can I write/read bytes/ints/longs to/from a file.

First of all, I'd like to tell you why do I need it. Basically I want to read data from a file which has a special format in it. All the data is written in binary in that file.

File format specification

I've already written that program in another language and I'd like to re-write my program in C++. The language I used previously is called BlitzMax and in that language function are already implemented and just called WriteByte, ReadByte, WriteInt, ReadInt etc.. If you guys will be kind enough to write (or at least link me the source) the functions I need, it will be much appreciated. And if you will write them for me, can you also explain how they work?

Thank you very much to everyone who will help me! :)

Edit: Here, as requested, the code that is somewhat does what I need. It does write the int 50 in binary to a file, but that's as far as I could go to. I still can't understand some parts (code was found in google, I edited it a bit). And I still need a way to write bytes and longs.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int num = 50
    ofstream file("file.txt", ios::binary);
    file.write(reinterpret_cast<const char *>(&num), sizeof(num));
    file.close ();
    return 0;
}
1

There are 1 answers

3
Giorgi Moniava On BEST ANSWER

Just follow in the same fashion:

int num = 50;
unsigned char x = 9;
float t = 9.0;

ofstream file("file.bin", ios::binary);
file.write(reinterpret_cast<const char *>(&num), sizeof(num));
file.write(reinterpret_cast<const char *>(&x), sizeof(x));
file.write(reinterpret_cast<const char *>(&t), sizeof(t));
file.close ();
return 0;

Some more info on reading.

But beware of portability issues when doing binary reading/writing. Portability issues maybe related to the fact that integer can be 4 bytes on your machine and have different size on other machine. Endianness is also another concern. Encoding floats is binary is also not portable (here).