gpt4 book ai didi

c - LzmaLib : compress/decompress buffer in C

转载 作者:太空狗 更新时间:2023-10-29 17:02:22 26 4
gpt4 key购买 nike

我正在尝试使用 LzmaLib带有缓冲区的 LzmaCompress()LzmaDecompress(),改编提供的示例 here .

我正在测试一个 ~3MB 的缓冲区,压缩函数似乎工作正常(产生一个 ~1.2MB 的压缩缓冲区),但是当我尝试解压缩时,它只提取了 ~300 字节并返回 SZ_ERROR_DATA.

提取出来的几个字节是对的,就是不知道为什么到此为止

我的代码:

#include <stdio.h>
#include <stdlib.h>

#include "LzmaLib.h"

void compress(
unsigned char **outBuf, size_t *dstLen,
unsigned char *inBuf, size_t srcLen)
{
unsigned propsSize = LZMA_PROPS_SIZE;
*dstLen = srcLen + srcLen / 3 + 128;

*outBuf = (unsigned char*)malloc(propsSize + *dstLen);

int res = LzmaCompress(
(unsigned char*)(*outBuf + LZMA_PROPS_SIZE), dstLen,
inBuf, srcLen,
*outBuf, &propsSize,
-1, 0, -1, -1, -1, -1, -1);

assert(res == SZ_OK);

*dstLen = *dstLen + LZMA_PROPS_SIZE;
}

void uncompress(
unsigned char **outBuf, size_t *dstLen,
unsigned char *inBuf, size_t srcLen
) {
*dstLen = 5000000;
*outBuf = (unsigned char*)malloc(*dstLen);

srcLen = srcLen - LZMA_PROPS_SIZE;
int res = LzmaUncompress(
*outBuf, dstLen,
(unsigned char*)(inBuf + LZMA_PROPS_SIZE), &srcLen,
inBuf, LZMA_PROPS_SIZE);

assert(res == SZ_OK);
}

void do_compress() {
FILE* file = fopen("Module.dll", "r");
size_t size, decSize;
unsigned char *data, *dec = NULL;

fseek(file, 0L, SEEK_END);
size = ftell(file);
fseek(file, 0L, SEEK_SET);

data = (unsigned char*)malloc(size);
fread(data, 1, size, file);
fclose(file);

compress((unsigned char**)&dec, &decSize, data, size);

file = fopen("Module.lzma", "w");
fwrite(dec, 1, decSize, file);
fclose(file);
}

void do_uncompress() {
FILE* file = fopen("Module.lzma", "r");
size_t size, decSize;
unsigned char *data, *dec = NULL;

fseek(file, 0L, SEEK_END);
size = ftell(file);
fseek(file, 0L, SEEK_SET);

data = (unsigned char*)malloc(size);
fread(data, 1, size, file);
fclose(file);

uncompress((unsigned char**)&dec, &decSize, data, size);

file = fopen("Module_DEC.dll", "w");
fwrite(dec, 1, decSize, file);
fclose(file);
}

int main()
{
do_compress();
do_uncompress();

return 0;
}

如果这段代码不是使用 LzmaLib 压缩缓冲区的更好方法,我很乐意接受建议。

最佳答案

我敢打赌问题出在您读取/写入文件的方式上。您需要以二进制模式打开它们以防止在读/写操作期间进行任何替换。

更改所有实例:

  • fopen(xxx, "r") -> fopen(xxx, "rb")
  • fopen(xxx, "w") -> fopen(xxx, "wb")

关于c - LzmaLib : compress/decompress buffer in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40732966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com