3

我正在尝试使用 c++ 和 libzip 库解压缩可执行文件。从 rodrigo 对类似问题的回答开始,我来到这个示例代码:

#include <zip.h>
int main()
{
    //Open the ZIP archive
    int err = 0;
    zip *z = zip_open("foo.zip", 0, &err);

    //Search for the file of given name
    const char *name = "file.txt";
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(z, name, 0, &st);

    //Alloc memory for its uncompressed contents
    char *contents = new char[st.size];

    //Read the compressed file
    zip_file *f = zip_fopen(z, "file.txt", 0);
    zip_fread(f, contents, st.size);
    zip_fclose(f);

    //And close the archive
    zip_close(z);
}

据我了解,这段代码确实可以解压缩文件,但我不知道如何将该文件写入磁盘,就像使用 winzip 之类的工具提取 zip 文件一样。将解压缩的数据放在内存中对我没有帮助,但我一直无法弄清楚如何将文件实际放到磁盘上。

4

1 回答 1

2

这样的事情应该这样做:

if(!std::ofstream("file1.txt").write(contents, st.size))
{
    std::cerr << "Error writing file" << '\n';
    return EXIT_FAILURE;
}

查找std::ofstream

当然,zip在继续之前,您应该检查所有文件函数以查看它们是否返回错误。

于 2016-02-11T18:38:52.767 回答