如何使用C ++中的libbz2压缩目录 [英] How to compress a directory with libbz2 in C++

查看:238
本文介绍了如何使用C ++中的libbz2压缩目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个目录的压缩包,然后在C ++中用bz2压缩它。关于使用libtar和libbz2有什么体面的教程吗?

I need to create a tarball of a directory and then compress it with bz2 in C++. Is there any decent tutorial on using libtar and libbz2?

推荐答案

好,我为你做了一个快速的例子。没有错误检查和各种任意决定,但它的工作原理。 libbzip2具有相当的良好的网络文档。 libtar,不是那么多,但在包中有一个manpages,一个例子和一个记录的头文件。下面可以用 g ++ C +建立tarBz2.cpp -ltar -lbz2 -o C ++ TarBz2.exe

Okay, I worked up a quick example for you. No error checking and various arbitrary decisions, but it works. libbzip2 has fairly good web documentation. libtar, not so much, but there are manpages in the package, an example, and a documented header file. The below can be built with g++ C++TarBz2.cpp -ltar -lbz2 -o C++TarBz2.exe:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <libtar.h>
#include <bzlib.h>
#include <unistd.h>

int main()
{
    TAR *pTar;
    char tarFilename[] = "file.tar";
    char srcDir[] = "dirToZip/";
    char extractTo[] = ".";

    tar_open(&pTar, tarFilename, NULL, O_WRONLY | O_CREAT, 0644, TAR_GNU);
    tar_append_tree(pTar, srcDir, extractTo);

    close(tar_fd(pTar));

    int tarFD = open(tarFilename, O_RDONLY);

    char tbz2Filename[] =  "file.tar.bz2";
    FILE *tbz2File = fopen(tbz2Filename, "wb");
    int bzError;
    const int BLOCK_MULTIPLIER = 7;
    BZFILE *pBz = BZ2_bzWriteOpen(&bzError, tbz2File, BLOCK_MULTIPLIER, 0, 0);

    const int BUF_SIZE = 10000;
    char* buf = new char[BUF_SIZE];
    ssize_t bytesRead;
    while((bytesRead = read(tarFD, buf, BUF_SIZE)) > 0) {
        BZ2_bzWrite(&bzError, pBz, buf, bytesRead);
    }        
    BZ2_bzWriteClose(&bzError, pBz, 0, NULL, NULL);
    close(tarFD);
    remove(tarFilename);

    delete[] buf;

}

这篇关于如何使用C ++中的libbz2压缩目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆