我正在尝试通过 C++ 在特定位置写入大小为 1 MB 的现有空白二进制文件。
ofstream of( filename, ofstream::binary );
of.seekp(1600, of.beg);
of.write(arr, 1024);
of.close();
空白文件是通过将此缓冲区写入文件之前创建的:
char *buffer = (char*)malloc(size);
memset(buffer, ' ', size);
但是这段代码只是截断了整个1MB的空白文件并写入了这1KB的内容,文件的大小变成了1KB。
也尝试使用 app
以及 ate
模式。当我像这样尝试 app
模式时:
ofstream of( filename, ofstream::binary | ofstream::app );
of.seekp(1600, of.beg);
of.write(arr, 1024);
of.close();
它将内容添加到文件末尾。因此文件大小为 1MB+1KB。
我想做的是用一些数据覆盖文件中的 1KB 数据(目前它是空白空间)。这样它就不会更改文件大小或任何其他数据。
我哪里做错了?
最佳答案
使用
ofstream of( filename, ofstream::binary | ofstream::in | ofstream::out)
打开二进制文件进行更新。
参见 C++11 表 123 - 文件打开模式(在 27.9.1.4/3 中):
Table 132 — File open modes
ios_base flag combination stdio
binary in out trunc app equivalent
---------------------------------------------------
+ "w" truncate/create for writing
+ + "a" append - writes automatically seek to EOF
+ "a"
+ + "w"
+ "r" open for read
---------------------------------------------------
+ + "r+" open for update (reading and writing)
+ + + "w+" truncate/create for update
+ + + "a+" open or create for update - writes seek to EOF
+ + "a+"
---------------------------------------------------
+ + "wb" All same as above, but in binary mode
+ + + "ab"
+ + "ab"
+ + + "wb"
+ + "rb"
---------------------------------------------------
+ + + "r+b"
+ + + + "w+b"
+ + + + "a+b"
+ + + "a+b"
关于c++ - 在 C++ 中写入现有的空格二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597118/