c++ - 如何在C++中按字节写入文件

标签 c++ c

我想在指定的文件位置写入 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/

相关文章:

c++ - 如何使用概念将参数传递给类方法?

c++ int指向数组指针数组的指针内存泄漏

C++赋值运算符,我们可以用copy来代替它吗?

c - 宏中的双重科学记数法

c - 下标值既不是数组也不是指针也不是 vector 的错误

python - boost-python 当 C++ 方法返回 std::map<string,X*>

c++ - Dev C++ 系列总和 "cannot be used as a function"

java - 数组中没有重复项

c++ - 如何使用 C++ 在 Windows 中添加虚拟文件夹

c - 简单的 C 程序没有给出预期的输出