【问题标题】:C++ compressing using lz4, compressed information not as expectedC++ 使用 lz4 压缩,压缩信息不如预期
【发布时间】:2017-07-15 06:53:40
【问题描述】:

我在 mac 上使用 lz4 并在我的程序中做一个压缩字符串(命名为 str)的实验。

#include <fstream>
#include <iostream>
#include "lz4.h"
using namespace std;
int main(){
    char str[] = "10100100010000100000100000010000000100000000100000000010000000000";
    size_t len = sizeof(str);
    char* target = new char[len];
    int nCompressedSize = LZ4_compress_default((const char *)(&str), target, len, len);

    ofstream os("lz4.dat",ofstream::binary);
    os.write(target, nCompressedSize);
    os.close();
    delete[] target;
    target = 0;

    ifstream is( "lz4.dat", ifstream::binary );
    is.seekg (0,is.end);
    size_t nCompressedInputSize = is.tellg();
    is.clear();
    is.seekg(0,ios::beg);

    //Read file into buffer
    char* in = new char[nCompressedInputSize];
    int32_t n=is.read(in,nCompressedSize);
    cout<<"Byte number:"<<nCompressedSize<<",file size:"<<n<<",bytes read:"<<in<<endl;
    is.close();
    return 0;
}

运行这个程序,我检查了“lz4.dat”文件:

$ls -lrt lz4.dat
-rw-r--r--  1 x  staff  34  7 15 14:50 lz4.dat

34字节,OK,但是程序输出的是:

Byte number:34,file size:1,bytes read:@1010

很奇怪,收到的文件大小好像是1字节,我实际上输出了一些随机@1010。为什么我的“is.tellg()”没有得到正确的文件长度?

谢谢。

【问题讨论】:

  • 你检查过 nCompressedSize 吗?它是否大于 34 字节?关键是如果字符串很小,压缩字符串可能比初始字符串长

标签: c++ file compression fstream lz4


【解决方案1】:

ifstream::read() 不返回读取的字节。它返回一个对*this 的引用,它有operator bool(),我认为它是用于以防万一的。所以你在n,你就知道操作是否成功了。

输出似乎完全没问题,它是压缩数据的开始。我认为只打印了几个字节,因为它包含一个终止零。它类似于您的输入,因为 lz4 将文字逐字放入流中(lz4 没有熵编码)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2016-05-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 2014-02-03
    相关资源
    最近更新 更多