使用 libarchive 库将文件夹打包成tar文件可直接使用的代码
时间: 2024-02-20 14:01:16 浏览: 40
以下是使用 libarchive 库将文件夹打包成tar文件的完整代码:
```c++
#include <stdio.h>
#include <stdlib.h>
#include <archive.h>
#include <archive_entry.h>
int main(int argc, char** argv) {
if (argc < 3) {
printf("Usage: %s <input_dir> <output_file>\n", argv[0]);
return 1;
}
const char* input_dir = argv[1];
const char* output_file = argv[2];
struct archive* ar = archive_write_new();
archive_write_add_filter_gzip(ar); // 添加 gzip 压缩
archive_write_set_format_pax_restricted(ar); // 使用 tar 格式
if (archive_write_open_filename(ar, output_file) != ARCHIVE_OK) {
printf("Failed to open output file: %s\n", archive_error_string(ar));
return 1;
}
struct archive* ar_input = archive_read_new();
archive_read_support_format_tar(ar_input);
archive_read_support_filter_gzip(ar_input);
if (archive_read_open_filename(ar_input, input_dir, 10240) != ARCHIVE_OK) {
printf("Failed to open input directory: %s\n", archive_error_string(ar_input));
return 1;
}
while (1) {
struct archive_entry* entry;
int r = archive_read_next_header(ar_input, &entry);
if (r == ARCHIVE_EOF) {
break;
}
if (r != ARCHIVE_OK) {
printf("Failed to read next header: %s\n", archive_error_string(ar_input));
return 1;
}
archive_write_header(ar, entry);
if (archive_entry_size(entry) > 0) {
char buf[10240];
ssize_t len;
while ((len = archive_read_data(ar_input, buf, 10240)) > 0) {
if (archive_write_data(ar, buf, len) != len) {
printf("Failed to write data: %s\n", archive_error_string(ar));
return 1;
}
}
}
}
archive_read_close(ar_input);
archive_read_free(ar_input);
archive_write_close(ar);
archive_write_free(ar);
printf("Successfully created tar file %s\n", output_file);
return 0;
}
```
其中 `input_dir` 和 `output_file` 分别表示输入的文件夹路径和输出的 tar 文件路径。该代码会将输入文件夹中的所有文件和目录打包成 tar 文件,并使用 gzip 压缩。需要注意的是,上述代码中只展示了基本的打包流程,实际使用时还需要添加错误处理和资源释放等代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)