繁体   English   中英

使用zlib1.2.7解压缩gzip数据,如何在压缩包中获取文件名

[英]Using zlib1.2.7 uncompress gzip data,how to get the files' name in the compression package

使用zlib版本1.2.7解压缩gzip数据,但我不知道如何在压缩包或正在提取的压缩包中获取文件名。我找到的方法看起来像是读取所有数据以缓冲,然后然后退货。

像这样:

int gzdecompress(Byte *zdata, uLong nzdata, Byte *data, uLong *ndata)
{
    int err = 0;
    z_stream d_stream = {0}; /* decompression stream */
    static char dummy_head[2] = {
        0x8 + 0x7 * 0x10,
        (((0x8 + 0x7 * 0x10) * 0x100 + 30) / 31 * 31) & 0xFF,
    };
    d_stream.zalloc = NULL;
    d_stream.zfree = NULL;
    d_stream.opaque = NULL;
    d_stream.next_in  = zdata;
    d_stream.avail_in = 0;
    d_stream.next_out = data;
    //only set value "MAX_WBITS + 16" could be Uncompress file that have header or trailer text
    if(inflateInit2(&d_stream, MAX_WBITS + 16) != Z_OK) return -1;
    while(d_stream.total_out < *ndata && d_stream.total_in < nzdata) {
        d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */
        if((err = inflate(&d_stream, Z_NO_FLUSH)) == Z_STREAM_END) break;
        if(err != Z_OK) {
            if(err == Z_DATA_ERROR) {
                d_stream.next_in = (Bytef*) dummy_head;
                d_stream.avail_in = sizeof(dummy_head);
                if((err = inflate(&d_stream, Z_NO_FLUSH)) != Z_OK) {
                    return -1;
                }
            } else return -1;
        }
    }
    if(inflateEnd(&d_stream) != Z_OK) return -1;
    *ndata = d_stream.total_out;
    return 0;
}

使用示例:

// file you want to extract
filename = "D:\\gzfile";

// read file to buffer
ifstream infile(filename, ios::binary);
if(!infile)
{
    cerr<<"open error!"<<endl;
}
int begin = infile.tellg();
int end = begin;
int FileSize = 0;
infile.seekg(0,ios_base::end);
end = infile.tellg();
FileSize = end - begin;

char* buffer_bin = new char[FileSize];
char buffer_bin2 = new char[FileSize * 2];

infile.seekg(0,ios_base::beg);
for(int i=0;i<FileSize;i++)
    infile.read(&buffer_bin[i],sizeof(buffer_bin[i]));
infile.close( );

// uncompress 
uLong ts = (FileSize * 2);
gzdecompress((Byte*)buffer_bin, FileSize, (Byte*)buffer_bin2, &ts);

数组“ buffer_bin2”获取提取的数据。属性“ ts”是数据长度。

问题是,我不知道它的名字,只有一个文件,如何获取信息?

您的问题根本不清楚,但是如果您尝试获取存储在gzip标头中的文件名,那么您应该阅读zlib.h中的zlib文档。 实际上,如果您计划以任何能力使用zlib,那将是个好主意。

在文档中,您会发现inflateGetHeader() inflate...()函数将解压缩gzip数据,并且有一个inflateGetHeader()函数将返回gzip标头的内容。

请注意,当gzip解压缩.gz文件时,除非明确要求,否则它甚至不会查看标头中的名称。 gzip将解压缩为.gz文件的名称,例如foo.gz解压缩foo.gz变为foo ,即使gzip标头中的名称为bar 如果使用gzip -dN foo.gz ,它将称其为bar 不清楚您为什么还要关心gzip标头中的名称是什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM