views:

592

answers:

2

Hi

I have this code that I found somewhere on stackoverflow that uses libtar and libbz2 to compress a directory:

#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;
}

Although it creates a bz2 file and its size seems to be right ( 1,7 MB from a 5MB directory) but the archive itself is corrupted, I cannot open it neither with ark nor with command line tar. What is the problem?

+3  A: 

tar and bz2 are different steps of the process if you will. Tar concatenates a bunch of files together into one file with an index, and then bzip2 compresses that single file.

To extract manually, go in the reverse order. On a unix/linux system:

bunzip2 file.tar.bz2

should give you a .tar file, then you can

tar -xvf file.tar

to extract things from the tar file (also referred to as a tarball).

Michael Kohne
A: 

tar xjf thefile.tar.bz2 works with modern tar implementations, such as gnu's.

Alex Martelli