gpt4 book ai didi

c++ - 如果保存数据,libz 压缩失败

转载 作者:行者123 更新时间:2023-11-30 02:51:22 27 4
gpt4 key购买 nike

我刚刚遇到了 libz 的一个非常奇怪的行为。如果我只是使用 compress 功能一切正常,但如果我尝试,例如。将压缩数据保存到文件,我收到 Z_BUF_ERROR。我做错了什么?

#include <iostream>
#include <fstream>

#include "zlib.h"

typedef unsigned char byte_t;

static int read_filesize(const char* filename) {
int size = -1;
std::ifstream file(filename);
if (!file.is_open()) return size;

file.seekg(0, std::ios::end);
size = (int) file.tellg();
file.close();

return size;
}

static bool read_binary_file(const char* filename, byte_t* dst, const unsigned length) {
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) return false;

file.read((char*) dst, length);
file.close();

return true;
}

static bool save_binary_file(const char* filename, const byte_t* src, const unsigned length) {
std::ofstream file(filename, std::ios::binary);
if (!file.is_open()) return false;

file.write((const char*) src, length);
file.close();

return true;
}

int main(int args, char **argv) {
int fileSize = read_filesize(argv[1]);
byte_t fileData[fileSize];
bool result = read_binary_file(argv[1], fileData, fileSize);

unsigned compressedSize = compressBound(fileSize);
byte_t compressed[compressedSize];

int compressionResult = compress(compressed, (unsigned long*) &compressedSize, fileData, fileSize);

switch (compressionResult) {
case Z_OK:
std::cout << "Compression succeeded!\n";
break;

case Z_MEM_ERROR:
std::cout << "Error: Z_MEM_ERROR!\n";
return 1;

case Z_BUF_ERROR:
std::cout << "Error: Z_BUF_ERROR!\n";
return 1;

default:
std::cout << "Error: UNDEFINED!\n";
return 1;
}

std::cout << "Size of '" << argv[1] << "': " << fileSize << "\n"
<< "After: " << compressedSize << "\n";

bool saveResult = save_binary_file("file.bin.z", compressed, compressedSize); // everything works if I remove this instruction

return 0;
}

最佳答案

从上面的评论看来,您使用的是 64 位架构,其中 sizeof(unsigned long)==8,而 sizeof(unsigned)==4

因此,转换 (unsigned long*)&compressedSize 其中 compressedSizeunsigned 类型,产生未定义的行为。

只需将 compressedSize 的声明更改为类型 unsigned long 即可解决此问题。

关于c++ - 如果保存数据,libz 压缩失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19725318/

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