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

[亡魂溺海] 提交于 2020-02-25 03:04:14

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/15095212/fseek-go-back-to-the-end-of-file-when-writing-a-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!