c++ - 如何使用 gzip 压缩压缩包?

标签 c++ linux gzip tar zlib

嘿,我想知道是否有人知道如何使用 gzip 压缩 tarball 文件。我查看了this已经成功压缩了一个 tarball,尽管我想用 gzip 而不是 libbz2 压缩那个 tarball。

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

有谁知道我如何实现这一点,最好是使用 zlib 库?

最佳答案

使用 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

关于c++ - 如何使用 gzip 压缩压缩包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4988236/

相关文章:

c++ - 在 GtkDialog 中创建一个循环

linux - 将网络打印机添加到任何 Linux 系统的批处理文件

c - 我如何在centOS6上获得 `tcp option timestamp`

c++ - 如何隐藏任务栏上的应用程序?

c++ - 是否存在合理的情况,其中 == 运算符不是 != 的否定?

c - Linux 中的物理位置感知用户空间内存分配(内存 Controller 亲和性)

html - 我可以 gzip 压缩我所有的 html 内容(页面)吗?

python - python 中更快、更好的gunzip(以及一般文件输入/输出)

python - tmpfile 和 gzip 组合问题

c++ - boost : problems with placement new 中的 load_construct_data