2017-07-15 157 views
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()」沒有得到正確的文件長度?

謝謝。

+0

你檢查過nCompressedSize了嗎?它是否大於34字節?重點是如果字符串很小,壓縮的字符串可能比初始字符串更長 –

回答

2

ifstream::read()不返回讀取的字節。它返回一個對*this的引用,其中有operator bool(),我認爲這是用在案例中。所以你在n,你會得到操作是否成功。

輸出似乎是完全正常的,它是壓縮數據的開始。我認爲只打印了幾個字節,因爲它包含一個終止零。它類似於你的輸入,因爲lz4將文字逐字地放入流中(lz4沒有熵編碼)