libarchive资料好少,倒腾好久弄出来个demo,用博客记一下
解压文件名是包含在压缩包中的相对文件路径的,要先创建在系统中对于的文件夹才能解压出来。
带中文字符的文件解压不出来,暂时没去排查原因。
libarchive库我查到的信息说是支持7z,但是实际操作下来没支持,不知道是不是编译的时候没编译好
#include <archive.h>
#include <archive_entry.h>
#include <iostream>
using namespace std;
#include <iostream>
#include <fstream>
using namespace std;
void GetFileHeader()
{
ifstream file(R"(C:\Users\Administrator\Desktop\QtQuickApplication2\QtQuickApplication2\74.zip)");
char buffer[11]; // 定义一个长度为11的字符数组,包括最后一个字符'\0'
file.read(buffer, 10); // 读取文件的前10个字符
buffer[10] = '\0'; // 字符数组最后一个字符赋值为'\0',表示字符串的结束
cout << "前10个字符为:" << buffer << endl; // 输出所读取的字符
file.close(); // 关闭文件
}
int example_unpress()
{
struct archive *a;
struct archive_entry *entry;
int r;
const char *password = "key"; //
const char *filePath = R"(C:\Users\Administrator\Desktop\QtQuickApplication2\QtQuickApplication2\74.zip)";
a = archive_read_new();
r = archive_read_support_format_all(a);
archive_read_set_options(a, "7zip:use_cryptography_extension=1");
if (r != ARCHIVE_OK) {
exit(1);
}
const char *format = NULL;
if (archive_read_add_passphrase(a, password) != ARCHIVE_OK) {
auto i = archive_error_string(a);
printf("Error adding passphrase: %s\n", i);
return 1;
}
r = archive_read_open_filename(a, filePath, 500 * 1240); // test.zip
if (r != ARCHIVE_OK) {
auto errInfo = archive_error_string(a);
cout << "Error opening compressed file." << endl;
return 1;
}
bool is_encrypted = archive_read_has_encrypted_entries(a);
int size = 1024 * 1024;
char *buff = new char[size];
while (1) {
r = archive_read_next_header(a, &entry);
if (r != ARCHIVE_OK) {
auto i = archive_error_string(a);
break;
}
format = archive_format_name(a);
// 获取文件名
const char *filename = archive_entry_pathname(entry); //;"tmp"
if (filename == nullptr) {
break;
}
cout << "Extracting: " << filename << endl;
// 打开文件并写入解压数据
FILE *file = fopen(filename, "wb");
if (!file) {
cout << "Error opening file." << endl;
return 1;
}
while (1) {
r = archive_read_data(a, buff, size);
if (r <= 0) {
auto i = archive_error_string(a);
break;
}
fwrite(buff, size, 1, file);
}
fclose(file);
}
delete[]buff;
archive_read_close(a);
archive_read_free(a);
return 0;
}