enum CmpType {GZIP, BZ2};
void PdoCompress(string fileName, CmpType ct)
{
stringstream cmd;
FILE *tarResStream;
if(ct == GZIP) {
// cmd << "tar -cvzf " << fileName << ".gz " << fileName << " 2<&1";
cmd << "gzip " << "-f " << fileName << " 2<&1";
}
else if(ct == BZ2) {
// cmd << "tar -cvjf " << fileName << ".bz2 " << fileName << " 2<&1";
}
tarResStream = popen(cmd.str().c_str(), "r");
char outch;
do {
outch = fgetc(tarResStream);
cout << outch;
if( feof(tarResStream) )
break;
}while ( 1 );
fclose(tarResStream);
}
uint32_t doDef(FILE *source, FILE *dest, int32_t level)
{
const int chunk = 65536;
int ret, flush;
unsigned have;
z_stream strm;
unsigned char in[chunk];
unsigned char out[chunk];
/* allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = &in[0];
//ret = deflateInit(&strm, level);
ret = deflateInit2(&strm, level,
16 + MAX_WBITS, 8, Z_DEFLATED,
Z_DEFAULT_STRATEGY);
if (ret != Z_OK)
return ret;
/* compress until end of file */
do {
strm.avail_in = fread(in, 1, chunk, source);
if (ferror(source)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = chunk;
strm.next_out = out;
ret = deflate(&strm, flush); /* no bad return value */
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
have = chunk - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
} while (strm.avail_out == 0);
assert(strm.avail_in == 0); /* all input will be used */
} while(flush != Z_FINISH);
assert(ret == Z_STREAM_END);
/* clean up and return */
(void)deflateEnd(&strm);
return Z_OK;
}
void CustomLogger::Rotate(string location, uint32_t rotateNum)
{
stringstream newName, zipFileName;
// FILE *newNameFile, *zipFile;
// rename the file
newName << location << rotateNum;
zipFileName << newName.str() << ".z";
cout << "newName: " << newName.str() << endl;
cout << "zipFileName: " << zipFileName.str() << endl;
rename(location.c_str(), newName.str().c_str());
// newNameFile = fopen(newName.str().c_str(), "rb");
// zipFile = fopen(zipFileName.str().c_str(), "wb");
// SET_BINARY_MODE(newNameFile);
// SET_BINARY_MODE(zipFile);
// doDef(newNameFile, zipFile, Z_DEFAULT_COMPRESSION);
// doDef(newNameFile, zipFile, Z_BEST_COMPRESSION);
string fName = GetFileName(newName.str());
PdoCompress(newName.str(), GZIP);
remove(newName.str().c_str());
// fclose(newNameFile);
// fclose(zipFile);
// zip the file
}
Добавлены только соответствующие методы. Решил эту проблему сам, используя старый добрый вызов popen в методе PdoCompress. При попытке использовать zlib вызов dflateInit2 всегда возвращал Z_STREAM_ERROR (-2). Полный код можно увидеть на https://github.com/jhjacobs/CPPCustomLog. Исходным кодом являются только три файла CustomLogger.h, CustomLogger. cpp и Hello. cpp.