我在 stackoverflow 的某个地方找到了这段代码,它使用 libtar 和 libbz2 来压缩目录:
#include <libtar.h>
#include <bzlib.h>
#include <fcntl.h>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
TAR *p_tar;
char extract_to[] = ".";
char *dst_path = argv[2];
char *src_path = argv[1];
tar_open(&p_tar,dst_path,NULL,O_WRONLY | O_CREAT,0644,TAR_GNU);
tar_append_tree(p_tar,src_path,extract_to);
close(tar_fd(p_tar));
int tar_fd = open(dst_path,O_RDONLY);
string bz2_file_name = dst_path;
bz2_file_name.append(".bz2");
FILE *bz2_file = fopen(bz2_file_name.data(),"wb");
int bz2_err;
const int BLOCK_MULTIPLIER = 7;
BZFILE *pbz = BZ2_bzWriteOpen(&bz2_err,bz2_file,BLOCK_MULTIPLIER,0,0);
const int BUF_SIZE = 10000;
char* buffer = new char[BUF_SIZE];
size_t bytes_read;
while((bytes_read=read(tar_fd,buffer,BUF_SIZE))>0)
{
BZ2_bzWrite(&bz2_err,pbz,buffer,bytes_read);
}
BZ2_bzWriteClose(&bz2_err,pbz,0,NULL,NULL);
close(tar_fd);
remove(dst_path);
return 0;
}
虽然它创建了一个 bz2 文件并且它的大小似乎是正确的(从 5MB 目录中的 1,7 MB)但是存档本身已损坏,我既不能用 ark 也不能用命令行 tar 打开它。问题是什么?