我目前正在尝试使用C ++编写二进制数据。要写入的数据应该在其他已经写入的数据的中间。要写入的数据只是零字节。
我的代码看起来像这样:
unsigned int length = 4;
unsigned int offset = 0;
string path = "test.bin";
fstream file;
file.open(path, ios::in | ios::out | ios::binary | ios::ate);
queue <char*> buffers;
bool allocated = false;
do {
file.seekg(offset);
cout << "Reading buffer items! Offset: " << file.tellg() << endl;
char* buffer = new char[length];
file.read(buffer, length);
if (file.gcount() != 0) {
buffers.push(buffer);
}
if (allocated) {
cout << "#1 Writing buffer items! Offset: " << file.tellp() << endl;
file.seekp(offset, ios::end);
cout << "#2 Writing buffer items! Offset: " << file.tellp() << endl;
char* writeBuffer = buffers.front();
buffers.pop();
file.write(writeBuffer, length);
} else {
file.seekp(offset);
cout << "Writing null bytes! Offset: " << file.tellp() << endl;
char* buffer = new char[length];
for (unsigned int i = 0; i < length; i++) {
buffer[i] = (char) 0x00;
}
file.write(buffer, length);
allocated = true;
}
offset += length;
} while (file.gcount() != 0 && !buffers.empty());
file.flush();
file.close();
鉴于test.bin
看起来像这样:
0x00 0x01 0x02 0x03 0x04 0x44
我在std上的当前输出是
Reading buffer items! Offset: 0
Writing null bytes! Offset: 0
Reading buffer items! Offset: 4
#1 Writing buffer items! Offset: -1
#2 Writing buffer items! Offset: -1
Reading buffer items! Offset: -1
#1 Writing buffer items! Offset: -1
#2 Writing buffer items! Offset: -1
文件看起来像那样:
0x00 0x00 0x00 0x00 0x04 0x44
我不知道为什么它不写'&34;转移&#34;二进制文件的一部分但是零字节以及为什么它没有正确设置输出序列的位置。
编辑:
以下是预期的文件输出:0x00 0x00 0x00 0x00 0x00 0x01 0x02 0x03 0x04 0x44