问题
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 readingw
— truncate to zero length or create text file for writinga
— append; open or create text file for writing at end-of-filerb
— open binary file for readingwb
— truncate to zero length or create binary file for writingab
— append; open or create binary file for writing at end-of-filer+
— open text file for update (reading and writing)w+
— truncate to zero length or create text file for updatea+
— append; open or create text file for update, writing at end-of-filer+b
orrb+
— open binary file for update (reading and writing)w+b
orwb+
— truncate to zero length or create binary file for updatea+b
orab+
— 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