How can I write into a specific location of a file? My file contains the following info:
100 msc
I want to update it as:
100 10 20 34 32 43 44
So I want to skip 100
and overwrite msc
with the new input array.
How can I write into a specific location of a file? My file contains the following info:
100 msc
I want to update it as:
100 10 20 34 32 43 44
So I want to skip 100
and overwrite msc
with the new input array.
The best way that I know of is to read in the complete contents of the file, and then use some string manipulations to overwrite what you need. Then you can write back the modified information to the same file, overwriting its contents.
ktodisco's method works well, but another option would be to open the file with read/write permissions, and move the file position pointer to the write place in the buffer, and then just write what you need to. C++ probably has specifics to do this, but do it cleanly with just the C
stdio
library. Something like this:You can use these as references: - fseek - fwrite
Hope I helped!
== EDIT ==
In C++ the
iostream
class seems to be able to do all of the above. See: iostreamFirst you have to understand that you can't modify files like that.
You can but its a little more tricky than that (as you need to have space).
So what you have to do is read the file and write it into a new file then re-name the file to the original.
Since you know exactly where to read to and what to insert do that first.