2011-02-14 100 views
0

嘿,我想知道如果有人知道我可以用gzip压缩tarball文件。我已经检出了this,并成功压缩了一个tarball,但我想用gzip而不是libbz2压缩该tarball。如何使用gzip压缩tarball?

我自己也尝试从zlib source code.实现从gzappend.c例如gztack功能,但最终得到一堆错误和自嘲警告,所以我想我不会得到太多出过时的例子。

有谁知道我可以如何实现这一点,最好与zlib库?

+2

到目前为止做到这一点,最简单的方法是将`z`选项传递给`tar`时你创建了tar文件。你想用C++做这件事的动机是什么? – 2011-02-14 02:05:54

回答

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 
0

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

编辑:当你标签的东西Linux的人倾向于假设专门和只有Linux的手段。当然tar不适用于Windows操作系统的标准安装,所以在这种情况下,是的,提供一个捆绑的zlib dll并且像John提到的那样使用zlib。

2

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

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