如何用gzip压缩tarball?

时间:2011-02-14 02:03:44

标签: c++ linux gzip tar zlib

嘿,我想知道是否有人知道如何用gzip压缩tarball文件。我已经检查了this并成功压缩了一个tarball,虽然我想用gzip而不是libbz2来压缩tarball。

我还尝试从zlib source code.gztack示例中实现gzappend.c函数,但最终得到了一堆错误并弃用了警告,所以我想我不会得到很多被弃用的例子。

有没有人知道如何实现这一目标,最好是使用zlib库?

4 个答案:

答案 0 :(得分:4)

使用zlib例程gzopen打开压缩流,gcwrite将数据写入并压缩,然后gzclose关闭它。这是一个将一个文件压缩到另一个文件的完整程序:

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <zlib.h>

int main(int argc, char **argv)
{
  if(argc < 3)
  {
    fprintf(stderr, "Usage: %s input output\n", argv[0]);
    return 1;
  }

  // Open input & output files
  FILE *input = fopen(argv[1], "rb");
  if(input == NULL)
  {
    fprintf(stderr, "fopen: %s: %s\n", argv[1], strerror(errno));
    return 1;
  }

  gzFile output = gzopen(argv[2], "wb");
  if(output == NULL)
  {
    fprintf(stderr, "gzopen: %s: %s\n", argv[2], strerror(errno));
    fclose(input);
    return 1;
  }

  // Read in data from the input file, and compress & write it to the
  // output file
  char buffer[8192];
  int N;
  while((N = fread(buffer, 1, sizeof(buffer), input)) > 0)
  {
    gzwrite(output, buffer, N);
  }

  fclose(input);
  gzclose(output);

  return 0;
}

像这样使用:

$ ./mygzip input output.gz
$ diff input <(gunzip < output.gz)  # Verify that it worked

答案 1 :(得分:2)

您是否尝试过使用zlib?这里有一个教程: http://www.zlib.net/zlib_how.html

当然,这是制作gzip文件的好方法。按照你所说的目标,我会假设使用popen()system()来运行一个程序并不是那么好(要求机器安装其他东西,更不用说它如果你要去的那么效率会低一些做了很多)。

答案 2 :(得分:0)

在shell中有一个明确的方法:

gzip ball.tar

您可以让C ++程序使用popen系统调用来运行命令。

您还可以编写一个模拟c ++ iostream的zlib包装器(例如http://www.cs.unc.edu/Research/compgeom/gzstream/

答案 3 :(得分:0)

构造tar命令的const char *参数字符串并将其传递到cstdlib.h中的system()函数可能是最简单的方法。或者使用popen(),如Foo Bah的回答所提到的那样。我发现很难相信您的目标平台包含没有targzip的平台,因为即使像BusyBox这样的恢复shell也可以访问tar。一旦system()/ popen()返回(显然检查返回代码是否成功),为压缩文件创建一个ifstream并用它做任何你想做的事。

编辑:当你标记某些内容时,Linux人们倾向于认为这意味着特别是Linux。当然tar不适用于Windows操作系统的标准安装,所以在这种情况下,是的,提供捆绑的zlib dll并使用zlib作为John提及。

相关问题