2009-12-09 61 views
2

我正在嘗試使用LZMA SDK來創建zip存檔(zip或.7z格式)。我已經下載並構建了SDK,我只想使用dll導出來壓縮或解壓縮幾個文件。當我使用LzamCompress方法時,它返回0(SZ_OK),就像它正常工作一樣。但是,在將緩衝區寫入文件並嘗試將其打開後,出現文件無法作爲存檔打開的錯誤。您可以幫助您使用LZMA(7zip)SDK創建zip存檔嗎?

這是我目前使用的代碼。任何建議,將不勝感激。

#include "lzmalib.h" 

typedef unsigned char byte; 

using namespace std; 

int main() 
{ 
    int length = 0; 
    char *inBuffer; 

    byte *outBuffer = 0; 
    size_t outSize; 
    size_t outPropsSize = 5; 
    byte * outProps = new byte[outPropsSize]; 

    fstream in; 
    fstream out; 

    in.open("c:\\temp\\test.exe", ios::in | ios::binary); 

    in.seekg(0, ios::end); 
    length = in.tellg(); 
    in.seekg(0, ios::beg); 

    inBuffer = new char[length]; 

    outSize = (size_t) length/20 * 21 + (1 << 16); //allocate 105% of file size for destination buffer 

    if(outSize != 0) 
    { 
     outBuffer = (byte*)malloc((size_t)outSize); 
     if(outBuffer == 0) 
     { 
      cout << "can't allocate output buffer" << endl; 
      exit(1); 
     } 
    } 

    in.read(inBuffer, length); 
    in.close(); 

    int ret = LzmaCompress(
     outBuffer, /* output buffer */ 
     &outSize, /* output buffer size */ 
     reinterpret_cast<byte*>(inBuffer),/* input buffer */ 
     length, /* input buffer size */ 
     outProps, /* archive properties out buffer */ 
     &outPropsSize,/* archive properties out buffer size */ 
     5, /* compression level, 5 is default */ 
     1<<24,/* dictionary size, 16MB is default */ 
     -1, -1, -1, -1, -1/* -1 means use default options for remaining arguments */ 
    ); 

    if(ret != SZ_OK) 
    { 
     cout << "There was an error creating the archive." << endl; 
     exit(1); 
    } 

    out.open("test.zip", ios::out | ios::binary); 

    out.write(reinterpret_cast<char*>(outBuffer), (int)(outSize)); 
    out.close(); 

    delete inBuffer; 
    delete outBuffer; 
} 
+0

你是如何打開文件的?您是否使用7zip歸檔程序或LZMA SDK中的其他功能? – 2009-12-09 16:53:16

+0

7zip和Windows zip文件夾實用程序。 – scottm 2009-12-09 16:55:44

+0

我也試圖做到這一點,但仍不成功。 需要注意的一些問題。1)首字節5個字節是標題屬性(outProps),接下來的8個字節是長度。 2)然後是壓縮數據。當我用這種方式寫的時候也失敗了。我想我們需要加'7','z'。我不確定。 – 2010-09-21 11:46:15

回答

1

我不知道LZMA明確,但據我所知,一般的壓縮,它看起來像你沒有,它可以讓一個解壓縮程序的任何標頭信息寫入壓縮比特流文件知道如何比特流被壓縮。

LzmaCompress()函數可能會將此信息寫入outProps。 SDK中應該有另一個功能,它將outBuffer中的壓縮比特流和outProps中的屬性並從它們中創建適當的歸檔。

+1

這就是我在想什麼,但該DLL只導出LzmaCompress和LzmaDecompress。 – scottm 2009-12-09 17:10:25

+0

如果你可以用LzmaDecompress解壓縮,那麼解決你的問題還是你有生成與7zip兼容的存檔? – 2009-12-09 17:17:26

+0

我認爲使用LzmaDecompress解壓縮會很好,但是當我嘗試時,輸出大小仍爲0,即使函數返回SZ_OK – scottm 2009-12-09 17:27:56

相關問題