3

我正在尝试使用LZMA SDK创建一个 zip 存档(.zip 或 .7z 格式)。我已经下载并构建了 SDK,我只想使用 dll 导出来压缩或解压缩一些文件。当我使用 LzamCompress 方法时,它返回 0 (SZ_OK),就好像它工作正常一样。但是,在我将缓冲区写入文件并尝试打开它后,我收到一个错误,即文件无法作为存档打开。

这是我目前正在使用的代码。任何建议,将不胜感激。

#include "lzmalib.h"

typedef unsigned char byte;

using namespace std;

int main()
{
    int length = 0;
    char *inBuffer;

    byte *outBuffer = 0;
    size_t outSize;
    size_t outPropsSize = 5;
    byte * outProps = new byte[outPropsSize];

    fstream in;
    fstream out;

    in.open("c:\\temp\\test.exe", ios::in | ios::binary);

    in.seekg(0, ios::end);
    length = in.tellg();
    in.seekg(0, ios::beg);

    inBuffer = new char[length];

    outSize = (size_t) length / 20 * 21 + ( 1 << 16 ); //allocate 105% of file size for destination buffer

    if(outSize != 0)
    {
        outBuffer = (byte*)malloc((size_t)outSize);
        if(outBuffer == 0)
        {
            cout << "can't allocate output buffer" << endl;
            exit(1);
        }
    }

    in.read(inBuffer, length);
    in.close();

    int ret = LzmaCompress(
        outBuffer, /* output buffer */
        &outSize, /* output buffer size */
        reinterpret_cast<byte*>(inBuffer),/* input buffer */
        length, /* input buffer size */
        outProps, /* archive properties out buffer */
        &outPropsSize,/* archive properties out buffer size */
        5, /* compression level, 5 is default */
        1<<24,/* dictionary size, 16MB is default */
        -1, -1, -1, -1, -1/* -1 means use default options for remaining arguments */
    );

    if(ret != SZ_OK)
    {
        cout << "There was an error creating the archive." << endl;
        exit(1);
    }

    out.open("test.zip", ios::out | ios::binary);

    out.write(reinterpret_cast<char*>(outBuffer), (int)(outSize));
    out.close();

    delete inBuffer;
    delete outBuffer;
}
4

1 回答 1

1

我不具体了解 LZMA,但根据我对压缩的一般了解,看起来您正在将压缩的比特流写入文件,而没有任何头信息可以让解压缩程序知道比特流是如何压缩的。

The LzmaCompress() function probably writes this information to outProps. There should be another function in the SDK that will take the compressed bit stream in outBuffer and the properties in outProps and create a proper archive from them.

于 2009-12-09T17:09:16.783 回答