c++ - fseek 写入值时回到文件末尾

标签 c++ c fseek

我试图覆盖文件中位置 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 reading
  • w — truncate to zero length or create text file for writing
  • a — append; open or create text file for writing at end-of-file
  • rb — open binary file for reading
  • wb — truncate to zero length or create binary file for writing
  • ab — append; open or create binary file for writing at end-of-file
  • r+ — open text file for update (reading and writing)
  • w+ — truncate to zero length or create text file for update
  • a+ — append; open or create text file for update, writing at end-of-file
  • r+b or rb+ — open binary file for update (reading and writing)
  • w+b or wb+ — truncate to zero length or create binary file for update
  • a+b or ab+ — append; open or create binary file for update, writing at end-of-file

关于c++ - fseek 写入值时回到文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15095212/

相关文章:

c++ - C++ 中的命名冲突 : How to access a struct member called "class"

c++ - 将注册表项 HANDLE 转换为 HKEY

c - 为什么在更新模式下读取和写入之间总是需要 fseek 或 fflush?

c++ - 如何在 C++ 中包装 CFtpFileFind 示例?

c++ - 第一个 push_back 中的 STL 列表超出范围

c - 使用 execlp 的更多过滤器参数

c - Windows下获取当前用户名

c - 将链表中的值插入到堆栈中

c - 从管道读取时如何在可移植 C 中寻求前进

c - 随机写入输出文件的顺序?