-4

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;
}
4

1 回答 1

0

只需按照相同的方式进行操作:

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;

有关阅读的更多信息。

但是在进行二进制读/写时要注意可移植性问题。可移植性问题可能与整数在您的机器上可以是 4 个字节并且在其他机器上具有不同大小的事实有关。字节顺序也是另一个问题。编码浮点数是二进制的也不是可移植的(这里)。

于 2015-05-05T13:26:46.947 回答