Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overwrite in the middle of a File

Tags:

c++

c

file

php

file-io

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

like image 353
Neel Basu Avatar asked Dec 21 '10 07:12

Neel Basu


Video Answer


1 Answers

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.

like image 182
Thanatos Avatar answered Sep 26 '22 01:09

Thanatos