fseek go back to the end of file when writing a va

2019-07-20 04:02发布

I am trying to override 4 bytes at position 4 in a file, but fseek seems not to be working.

My code:

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 was open with "ab". The output is:

fseek returns 0
ftell 4
fwrite returns 1
ftell 2822716

The value was not overriden, but instead it was written at the end of file. What could cause that weird behaviour with fseek?

标签: c++ c fseek
2条回答
成全新的幸福
2楼-- · 2019-07-20 04:23

Opening in "ab" mode will result you in adding bytes at the end of the file, you need to use "wb" mode instead to overwrite the bytes.

查看更多
够拽才男人
3楼-- · 2019-07-20 04:24

The "ab" mode means that every write will be appended to the file, regardless of position before the write.

If you don't want that, don't use the "a" flag.

Added later:

If you're opening an existing file for update, then "r+b" opens the file for reading and writing; "w+b" truncates the file when it is opened, but allows you to read what you've written.

The C99 standard (ISO/IEC 9899:1999 — not the current standard, but that will be very similar) says:

§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
查看更多
登录 后发表回答