我想在指定的文件位置写入 C++ 中的二进制文件,以便一次写入文件 1-5 个字节。我有一个整数列表:
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.
但我不知道应该如何按字节写入文件。
最佳答案
您可以使用指针和 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”变量。
关于c++ - 如何在C++中按字节写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17391735/