我试图覆盖文件中位置 4 的 4 个字节,但 fseek 似乎不起作用。
我的代码:
int r = fseek(cacheStream, 4, SEEK_SET);
std::cout << "fseek returns " << r << std::endl;
std::cout << "ftell " << ftell(cacheStream) << std::endl;
r = fwrite(&chunckSize, sizeof(uint32_t), 1, cacheStream);
std::cout << "fwrite returns " << r << std::endl;
std::cout << "ftell " << ftell(cacheStream) << std::endl;
cacheStream 是用“ab”打开的。输出是:
fseek returns 0
ftell 4
fwrite returns 1
ftell 2822716
该值未被覆盖,而是写入文件末尾。什么会导致 fseek 出现这种奇怪的行为?
最佳答案
"ab"
模式意味着每次写入都将附加到文件中,无论写入前的位置如何。
如果你不想这样,请不要使用 "a"
标志。
稍后添加:
如果您打开现有文件进行更新,则 "r+b"
打开文件进行读写; "w+b"
在打开文件时截断文件,但允许您阅读您所写的内容。
C99 标准(ISO/IEC 9899:1999 — 不是当前标准,但会非常相似)说:
§7.19.5.3 The
fopen
function
r
— open text file for readingw
— truncate to zero length or create text file for writinga
— append; open or create text file for writing at end-of-filerb
— open binary file for readingwb
— truncate to zero length or create binary file for writingab
— append; open or create binary file for writing at end-of-filer+
— open text file for update (reading and writing)w+
— truncate to zero length or create text file for updatea+
— append; open or create text file for update, writing at end-of-filer+b
orrb+
— open binary file for update (reading and writing)w+b
orwb+
— truncate to zero length or create binary file for updatea+b
orab+
— append; open or create binary file for update, writing at end-of-file
关于c++ - fseek 写入值时回到文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15095212/