5

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?

allejo
  • 2,076
  • 4
  • 25
  • 40

3 Answers3

4

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thank you very much! This worked perfectly. I figured I did something wrong with the streams as I'm not too familiar with them. – allejo Mar 02 '12 at 06:48
2

Try with libbzip2.

It's available in C.

https://www.sourceware.org/bzip2

For a code sample see: dlltest.c

A T
  • 13,008
  • 21
  • 97
  • 158
1

I modified the loop and it's working.

int BUF_SIZE = 1024 * 10;    
char* buf = new char[BUF_SIZE];
while(infile.tellg() >= 0) {
    infile.read(buf, BUF_SIZE);
    BZ2_bzWrite(&bzError, myBZ, buf, infile.gcount());
}    
BZ2_bzWriteClose(&bzError, myBZ, 0, NULL, NULL);
spcgh0st
  • 76
  • 4
  • 2
    This solution works in this context. It is necessary to pass infile.gcount() to BZ2_bzwrite. With the currently accepted solution, one ends up with an empty bz2 file. – Colin Bernet Jun 18 '14 at 11:43