The Problem is I am in the Middle of a File with fseek
Next exists some Bytes of Length m
that I want to replace with Bytes of length n
. simple write
will keep m-n
bytes still there. If m > n
and if m < n
some Bytes (n-m
) that I am not willing to change will be overwritten.
I just want to replace a known startPos to endPos
Byte Stream with variable length Bytes. What is the Best Solution.
-- EDIT -- Though It can be done by taking a Backup. do there exists any direct solution ? This is too Messy ? and Kind of Poor Coding.
o = fopen(original, 'r')
b = fopen(backup, 'w')
while(fpos(o) <= startPos){
buffer += fgetc(o)
}
fwrite(b, buffer)
fwrite(b, replaceMentBytes)
buffer = ""
fseek(o, endPos)
while(!feof(o)){
buffer += fgetc(o)
}
fwrite(b, buffer)
//now Copy backup to original
The most robust solution is to re-write the whole file, from scratch. Most operating systems will only let you overwrite bytes, not insert or remove them, from a file, so to accomplish that, you have to essentially copy the file, replacing the target bytes during the copy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With