C++将多个文件压缩成一个tar文件
时间: 2023-10-03 22:01:50 浏览: 47
你可以使用C++的tar库来压缩多个文件到一个tar文件中。以下是一个简单的示例代码,可以将多个文件打包成一个tar文件:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <archive.h>
#include <archive_entry.h>
int main(int argc, char** argv) {
// 检查参数是否正确
if (argc < 3) {
std::cerr << "Usage: " << argv[0] << " <output_tar_file> <input_file_1> [<input_file_2> ...]" << std::endl;
return 1;
}
// 打开tar文件
std::string tar_filename(argv[1]);
struct archive* tar = archive_write_new();
archive_write_set_format_pax_restricted(tar);
archive_write_open_filename(tar, tar_filename.c_str());
// 添加输入文件到tar文件中
for (int i = 2; i < argc; i++) {
std::string input_filename(argv[i]);
// 获取文件信息
struct archive_entry* entry = archive_entry_new();
archive_entry_clear(entry);
archive_entry_set_filetype(entry, AE_IFREG);
archive_entry_set_pathname(entry, input_filename.c_str());
archive_entry_set_size(entry, -1);
// 打开输入文件
std::ifstream input_file(input_filename, std::ios::binary);
if (!input_file.is_open()) {
std::cerr << "Failed to open input file: " << input_filename << std::endl;
return 1;
}
// 将文件写入tar文件
archive_write_header(tar, entry);
char buffer[4096];
while (input_file.read(buffer, sizeof(buffer)).gcount() > 0) {
archive_write_data(tar, buffer, input_file.gcount());
}
// 关闭输入文件
input_file.close();
archive_entry_free(entry);
}
// 关闭tar文件
archive_write_close(tar);
archive_write_free(tar);
return 0;
}
```
你可以将多个输入文件作为参数传递给该程序,例如:
```
./compress_file my_archive.tar file1.txt file2.txt file3.txt
```
该程序将创建一个名为`my_archive.tar`的tar文件,并将`file1.txt`、`file2.txt`和`file3.txt`添加到其中。