问题
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?
回答1:
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.
回答2:
Try with libbzip2.
It's available in C.
http://bzip.org/
For a code sample see: dlltest.c
回答3:
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);
来源:https://stackoverflow.com/questions/9494255/bz2-compression-in-c-with-bzlib-h