【发布时间】:2014-09-25 11:14:15
【问题描述】:
我的目标是删除二进制文件中的一个或多个部分。我通过仅将所需部分复制到第二个文件来做到这一点。我有两种方法。第一个应该将 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) 上使用它?
提前致谢
【问题讨论】:
-
你可以尝试初始化 i
-
没有改变 file2 只是原始 file1 的副本,并且程序卡在某个地方的循环中:(
标签: c binaryfiles file-copying lseek