我正在尝试通过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数据(目前是空白)。这样它就不会改变文件大小或任何其他数据。
我在哪里做错了?
答案 0 :(得分:3)
使用
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"