c++bzip2

BZ2 compression in C++ with bzlib.h


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?


Solution

  • 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.