如何用7z源码,解压tar.gz压缩包。请用c++写一段代码实现
时间: 2024-03-05 15:53:05 浏览: 140
可以使用libarchive库来解压缩tar.gz压缩包,以下是使用7z源码解压缩的C++代码示例:
```c++
#include <iostream>
#include <cstring>
#include <cstdio>
#include "7z.h"
#include "7zAlloc.h"
#include "7zCrc.h"
#include "7zFile.h"
#include "7zVersion.h"
using namespace std;
int extract_tar_gz(const char* archive, const char* extract_path){
CFileInStream archiveStream;
CLookToRead lookStream;
CSzArEx db;
SRes res;
UInt16 *temp = NULL;
size_t tempSize = 0;
int extractCount = 0;
ISzAlloc allocImp;
ISzAlloc allocTempImp;
allocImp.Alloc = SzAlloc;
allocImp.Free = SzFree;
allocTempImp.Alloc = SzAllocTemp;
allocTempImp.Free = SzFreeTemp;
CrcGenerateTable();
if (InFile_Open(&archiveStream.file, archive)){
cout << "Error: Can not open file " << archive << endl;
return -1;
}
FileInStream_CreateVTable(&archiveStream);
LookToRead_CreateVTable(&lookStream, False);
lookStream.realStream = &archiveStream.s;
LookToRead_Init(&lookStream);
SzArEx_Init(&db);
res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp);
if (res != SZ_OK){
cout << "Error: Can not open archive " << archive << endl;
return -1;
}
for (UInt32 i = 0; i < db.NumFiles; i++){
size_t offset = 0;
size_t outSizeProcessed = 0;
const CSzFileItem* fileItem = db.Files + i;
size_t len = SzArEx_GetFileNameUtf16(&db, i, NULL);
if (len > tempSize){
SzFree(NULL, temp);
tempSize = len;
temp = (UInt16*)SzAlloc(NULL, tempSize * sizeof(temp[0]));
}
SzArEx_GetFileNameUtf16(&db, i, temp);
char* filename = (char*)malloc(len * 2 + 1);
wcstombs(filename, (wchar_t*)temp, len * 2 + 1);
if (fileItem->IsDir){
continue;
}
if(strstr(filename, ".tar.gz") == NULL){
continue;
}
char cmd[100];
sprintf(cmd, "7z x -so \"%s\" 2>/dev/null | tar -xz -C \"%s\"", filename, extract_path);
system(cmd);
extractCount++;
free(filename);
}
SzArEx_Free(&db, &allocImp);
SzFree(NULL, temp);
File_Close(&archiveStream.file);
return extractCount;
}
int main(){
extract_tar_gz("test.tar.gz", "extract_path");
return 0;
}
```
代码中调用了系统的tar和7z命令,需要在Linux下运行。如果是在Windows下运行,需要修改命令行中的路径分隔符和/dev/null为nul。
阅读全文