My aim is to delete one ore more parts inside a binary file. I do this by only copying the needed parts to a second file. I have got two methods. The first one should append count bytes from File1 (with offset skip) to File2.
void copyAPart(struct handle* h, off_t skip, off_t count) {
struct charbuf *fileIn = NULL;
struct charbuf *fileOut = NULL;
fileIn = charbuf_create();
fileOut = charbuf_create();
int fin, fout, x, i;
char data[SIZE];
charbuf_putf(fileIn,"%s/File1", h->directory);
charbuf_putf(fileOut,"%s/File2", h->directory);
fin = open(charbuf_as_string(fileIn), O_RDONLY);
fout = open(charbuf_as_string(fileOut), O_WRONLY|O_CREAT, 0666);
lseek(fin, skip, SEEK_SET);
lseek(fout,0, SEEK_END);
while(i < count){
if(i + SIZE > count){
x = read(fin, data, count-i);
}else{
x = read(fin, data, SIZE);
}
write(fout, data, x);
i += x;
}
close(fout);
close(fin);
charbuf_destroy(&fileIn);
charbuf_destroy(&fileOut);
}
The second method should then append the rest of File1 (from skip to end) to File2
void copyUntilEnd(struct handle* h, off_t skip) {
struct charbuf *fileIn = NULL;
struct charbuf *fileOut = NULL;
fileIn = charbuf_create();
fileOut = charbuf_create();
int fin, fout, x, i;
char data[SIZE];
charbuf_putf(fileIn,"%s/File1", h->directory);
charbuf_putf(fileOut,"%s/File2", h->directory);
fin = open(charbuf_as_string(fileIn), O_RDONLY);
fout = open(charbuf_as_string(fileOut), O_WRONLY|O_CREAT, 0666);
lseek(fin, skip, SEEK_SET);
lseek(fout,0, SEEK_END);
x = read(fin, data, SIZE);
while(x>0){
write(fout, data, x);
x = read(fin, data, SIZE);
}
close(fout);
close(fin);
charbuf_destroy(&fileIn);
charbuf_destroy(&fileOut);
}
My questions are as follows:
- Why is this not working as expected?
- What would I need to change to use this on large files (>4GB) on 64Bit systems?
Thanks in advance