-1

一度に 1 ~ 5 バイトのファイルに書き込むように、指定されたファイル位置で C++ のバイナリ ファイルに書き込みたいと考えています。整数のリストがあります:

5 9 10 11 76 98 99999

ファイルにバイト単位で保存したいもの。値が次の形式でファイルに保存されるようにします。

filepointerWriter, 5
filepinterWriter+2, 9
filepinterWriter+8, 10
filepinterWriter+12, 76
filepinterWriter+16, 10 etc

次のようなファイルに書き込む方法を知っています。

ofstream f("f", ios::out | ios::binary);
f << 5; f << 9; f << 10; f << 76; // etc.

しかし、バイト単位でファイルに書き込む方法がわかりません。

4

1 に答える 1

0

たとえば、ポインターと memcpy を使用して実行できます。

次のものを保存したいとしましょう:

--------------------------------------------
|   bytes 0-3  |  bytes 4-5   | bytes 6-9  |
|      9       |     10       |     15     |
--------------------------------------------


int int1 = 9;
short short1 = 10;
int int2 = 15;

const int num_bytes = 10; // total bytes in the array
char str[num_bytes];
ZeroMemory(str, num_bytes);  // this will write zeros in the array

memcpy((void *)(str + 0), &int1, 4);    // length of integer 4 bytes
memcpy((void *)(str + 4), &short1, 2);  // length of short 2 bytes
memcpy((void *)(str + 6), &int2, 4);    // length of integer 4 bytes

次に、必要な方法を使用して「str」変数を書き込むことができます。

于 2013-06-30T15:53:20.327 に答える