libarchive,一个支持多种格式的压缩和归档的C语言库,包含常见的tar、cpio和zcat命令行工具的实现。
本文展示一个libarchive库C语言编程的tar.gz格式压缩文件示例。
简单代码示例:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include "archive.h"
#include "archive_entry.h"
void write_archive(const char *outname, const char **filename)
{
struct archive *a;
struct archive_entry *entry;
struct stat st;
char buff[1024];
int len;
int fd;
int ret;
a = archive_write_new();
archive_write_add_filter_gzip(a);
archive_write_set_format_pax_restricted(a);
archive_write_open_filename(a, outname);
while (*filename) {
stat(*filename, &st);
entry = archive_entry_new();
archive_entry_copy_pathname(entry, *filename);
archive_entry_set_mtime(entry, st.st_mtime, 0);
archive_entry_set_size(entry, st.st_size);