WriteFile and fwrite
I think there is a in-place re-write function which WriteFile supports, but fwrite does not support.
Suppose I have a file, and the content is "foo is content", I want to change the content of the file to "goo is content".
If I am using WriteFile API and open with CreateFile API (generic read | write, and open existing option), I can only write one byte 'g' to replace content in-place.
But when using fwrite, there is no in-place re-write function, and I have to use "a+" mode to open a file and re-write all content "goo is content". Right?
Are there similar functions in fwrite providing in-place re-write function?
thanks in advance,
Aren't you thinking of "w"? And have you tried?
To my experience writing to a file not being at EOF replaces characters.
I don't know what the standards has to say about it though.
yes that is correct, writing to a File before reaching EOF will replace characters in "w" mode.
The OP can use fseek as right pointed out by prog-bman!
To summarize: No, you don't have to rewrite the entire content. If you open the file in "a+" or "r+" mode, the file content is preserved, and you can use fseek to find any particular position in the file (either as a direct number of bytes from start, relative to the current position or relative the the end of the file [the latter is quite useful if you want to ADD something to the end of the file after having overwritten something in the beginning or middle of the file]).
fwrite willl just write the number of bytes you wish to write, where the current file-pointer is. The different modes of open decides whether the file is "emptied"(w) or "kept as is"(a) - and with a "+" added, it will allow both read and write. The difference between "w+", "r+" and "a+" is in the handling of the content of the file and whether the file needs to exist before you call fopen(). I believe "r+" means that writes happen at the start of the file, rather than at the end, if you don't use "fseek" to set the position.