C++ 使用 lz4 压缩,压缩信息不符合预期

标签 c++ file compression fstream lz4

我在 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()”没有得到正确的文件长度?

谢谢。

最佳答案

ifstream::read() 不返回读取的字节。它返回对 *this 的引用,其中有 operator bool(),我认为这是在 case 中使用的。所以你在 n 中,你会得到操作是否成功。

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

关于C++ 使用 lz4 压缩,压缩信息不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45115384/

相关文章:

c++ - 如何为模板类型创建别名?

c# - 如何在 C# 中读取自定义文件属性

javascript - 大数数组压缩

在C中使用BCD压缩数字字符串id

c++ - 在编译时检测模板存在

c++ - C/C++ 允许短路编译器优化

c++ - std::string 的解密有额外的填充字节?

javascript - 从本地文件运行时 $.get() 无法正常工作

android - 在 ListView 中显示文件列表

python - 使用 Python 位串测量霍夫曼编码的效率