几个月前我开始使用C ++,并试图用zlib压缩一块缓冲区,但是我没有使用fopen / fwrite将其压缩到一个文件中,而是想将整个缓冲区压缩成一个char数组,将其保存在内存中而不是写入磁盘。
这是我目前的代码:
int File::Write(const void *pBuffer,int nByte) {
if (!m_pFile || !m_bWrite)
return 0;
m_Stream.next_in = (Bytef*)pBuffer;
m_Stream.avail_in = (uInt)nByte;
int err = deflate(&m_Stream, Z_NO_FLUSH);
while (m_Stream.avail_out == 0) {
size_t nWritten = fwrite(m_Buffer,1,sizeof(m_Buffer),m_pFile);
if(nWritten<sizeof(m_Buffer)) return 0;
m_Stream.avail_out = sizeof(m_Buffer);
m_Stream.next_out = m_Buffer;
err = deflate(&m_Stream, Z_NO_FLUSH);
}
return nByte;
}
bool File::Close() {
int err;
if(m_bWrite) {
/* Finish the stream, still forcing small buffers: */
for (;;) {
err = deflate(&m_Stream, Z_FINISH);
fwrite(m_Buffer, 1, sizeof(m_Buffer) - m_Stream.avail_out, m_pFile);
m_Stream.avail_out = sizeof(m_Buffer);
m_Stream.next_out = m_Buffer;
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "deflate");
}
err = deflateEnd(&m_Stream);
fclose(m_pFile);
m_pFile = NULL;
} else {
err = inflateEnd(&m_Stream);
fclose(m_pFile);
m_pFile = NULL;
}
return true;
}