1
我在mac上使用lz4并做了一个实验来压缩我的程序中的字符串(名为str)。使用lz4进行C++压缩,压缩信息不如预期
#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个字节,我实际上输出了一些randome @ 1010。为什么我的“is.tellg()”没有得到正确的文件长度?
谢谢。
你检查过nCompressedSize了吗?它是否大于34字节?重点是如果字符串很小,压缩的字符串可能比初始字符串更长 –