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?
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.
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: