我的目标是删除二进制文件中的一个或多个部分。我通过仅将所需部分复制到第二个文件来做到这一点。我有两种方法。第一个应该将来自 File1 的count字节(带有偏移量skip)附加到 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);
}
然后,第二种方法应将 File1 的其余部分(从跳过到结束)附加到 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);
}
我的问题如下:
- 为什么这没有按预期工作?
- 我需要更改什么才能在 64 位系统上的大文件(>4GB)上使用它?
提前致谢