使用 libzip 将文件解压缩到磁盘

Unzipping a file to disk using libzip

本文关键字:磁盘 解压缩 文件 libzip 使用      更新时间:2023-10-16

我正在尝试使用 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 文件一样。将解压缩的数据放在内存中对我没有帮助,但是我一直无法弄清楚如何将文件实际放入磁盘。

这样的事情应该这样做:

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

查找 std::ofstream。

当然,您应该检查所有zip文件函数,看看它们是否返回了错误,然后再继续。