【问题标题】:C deleting parts of a large binary with lseek/read/writeC 使用 lseek/read/write 删除大型二进制文件的一部分
【发布时间】: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);
}

我的问题如下:

  1. 为什么没有按预期工作?
  2. 我需要更改哪些内容才能在 64 位系统上的大文件 (>4GB) 上使用它?

提前致谢

【问题讨论】:

  • 你可以尝试初始化 i
  • 没有改变 file2 只是原始 file1 的副本,并且程序卡在某个地方的循环中:(

标签: c binaryfiles file-copying lseek


【解决方案1】:

i初始化为0。

i的类型更改为off_t,将x的类型更改为ssize_t

检查copyAPartreadwrite的返回值。如果是0,则您已到达EOF,如果是-1,则会发生错误。

当涉及到大文件时,您需要查看编译器的手册。它应该指定您是否需要做任何额外的操作来操作大文件。

【讨论】:

    猜你喜欢
    • 2011-09-20
    • 2011-03-31
    • 2021-09-25
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 2012-09-28
    相关资源
    最近更新 更多