Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BZ2 compression in C++ with bzlib.h

Tags:

c++

bzip2

I currently need some help learning how to use bzlib.h header. I was wondering if anyone would be as so kind to help me figure out a compressToBZ2() function in C++ without using any Boost libraries?

void compressBZ2(std::string file)
{
std::ifstream infile;
int fileDestination = infile.open(file.c_str());

char bz2Filename[] = "file.bz2";
FILE *bz2File = fopen(bz2Filename, "wb");
int bzError;
const int BLOCK_MULTIPLIER = 7;
BZFILE *myBZ = BZ2_bzWriteOpen(&bzError, bz2File, BLOCK_MULTIPLIER, 0, 0);

const int BUF_SIZE = 10000;
char* buf = new char[BUF_SIZE];
ssize_t bytesRead;

while ((bytesRead = read(fileDestination, buf, BUF_SIZE)) > 0)
{
    BZ2_bzWrite(&bzError, myBZ, buf, bytesRead);
}

BZ2_bzWriteClose(&bzError, myBZ, 0, NULL, NULL);

delete[] buf;
}

What I've been trying to do is use something like this but I've had no luck. I am trying to get a .bz2 file not .tar.bz2

Any help?

like image 705
allejo Avatar asked Feb 29 '12 06:02

allejo


2 Answers

These two lines are wrong:

int fileDestination = infile.open(file.c_str());

// ...

while ((bytesRead = read(fileDestination, buf, BUF_SIZE)) > 0)

This isn't how std::ifstream works. For example, if you look at std::ifstream::open it doesn't return anything. It seems you are mixing up the old system calls open/read with the C++ stream concept.

Just do:

infile.open(file.c_str());

// ...

while (infile.read(buf, BUF_SIZE))

I recommend you read up more on using streams.

like image 141
Some programmer dude Avatar answered Sep 19 '22 14:09

Some programmer dude


Try with libbzip2.

It's available in C.

https://www.sourceware.org/bzip2

For a code sample see: dlltest.c

like image 38
A T Avatar answered Sep 23 '22 14:09

A T