views:

131

answers:

1

Hi,

All I can find using fopen() and fwrite() in C is to delete all contents and start writing again or append to the end of the file. What if I need to go to some offset in the file and overwrite a few bytes?

Is that possible with some function?

+3  A: 

You can open the file with the "rb+" option and then use fseek with SEEK_SET to go to a specific location. Therb+ opens it for both reading and writing as a binary file (the file must exist in order for it to succeed - it will not create a new file).

Mark Wilkins
That will overwrite just the bytes I want and will not append?
Nazgulled
The question is, will it discard the remainder of the file beyond what you've written?
Joe Koberg
@Nazgulled: Yes - the SEEK_SET positions to a specific byte offset in the file. SEEK_CUR can also be used to seek to an offset from the current location.
Mark Wilkins
@Joe: No, it will leave the remaining data unchanged.
Mark Wilkins