Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top