CGZip,一个C++ gzip方法封装






4.36/5 (14投票s)
2002年11月18日
1分钟阅读

351406

9742
一个用于处理zlib库中gzip方法的最小类。
描述
本文档介绍CGZip
,一个C++类,用于封装zlib库中的gzip方法。该类的目的是提供一个简单的类,用于压缩和解压缩缓冲区。
该类的主要特性是:
- 将
LPCTSTR
压缩和解压缩到文件 - 将内存缓冲区压缩和解压缩到文件
- 非MFC
- 隐藏zlib,因此您无需分发zlib头文件
- 符合UNICODE标准
示例
在示例中,我们假设以下代码片段位于顶部
// CGZip is in the zlib namespace using namespace zlib; CGZip gzip;
压缩内存缓冲区或字符串
首先,让我们打开一个文件进行写入
if(!gzip.Open(_T("myFile.gz"), CGZip::ArchiveModeWrite))) { // the file could not be opened... }
如您所见,Open
在成功时返回true
,否则返回false
。 几乎所有方法都具有这种行为。
现在我们可以将数据和字符串发送到文件
字符串
LPCTSTR szString = _T("This is a test string\n"); // writing string gzip.WriteString(szString);
缓冲区 (Buffers)
void* pBuffer; // a memory buffer int len; // size in bytes of the memory buffer // writing buffer gzip.WriteBuffer(pBuffer,len);
完成时,您必须关闭文件
gzip.Close();
请注意,如果gzip
超出作用域,它将自动关闭。
解压缩缓冲区或字符串
读取行为与写入行为非常相似。 首先,打开一个文件进行读取
if(!gzip.Open(_T("myFile.gz"), CGZip::ArchiveModeRead))) { // the file could not be opened... }
现在,您可以读取固定长度的缓冲区或整个文件
整个文件
void* pBuffer=NULL; int len=0; // reads and unzip the hole file, len contains the resulting size of pBuffer gzip.ReadBuffer(&pBuffer,&len); // pBuffer now contains len read bytes ... // don't forget to delete pBuffer if (pBuffer) delete[] pBuffer;
固定长度的缓冲区
int len; char* pBuffer[len]; // reads and unzip the hole file, len contains the resulting size of pBuffer gzip.ReadBufferSize(pBuffer,len);
类参考
详细的类参考资料以压缩HTML格式提供(由Doxygen生成)。
GZip 许可
这段代码完全且绝对可以用于商业和非商业用途。 但是,它使用zlib,因此您在使用它之前应检查zlib许可。 它包含在源代码中,但这里也提供:
//zlib.h -- interface of the 'zlib' general purpose compression library //version 1.1.4, March 11th, 2002 //Copyright (C) 1995-2002 Jean-loup Gailly and Mark Adler //This software is provided 'as-is', without any express or implied //warranty. In no event will the authors be held liable for any damages //arising from the use of this software. //Permission is granted to anyone to use this software for any purpose, //including commercial applications, and to alter it and redistribute it //freely, subject to the following restrictions: //1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. //2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. //3. This notice may not be removed or altered from any source distribution. //Jean-loup Gailly Mark Adler //jloup@gzip.org madler@alumni.caltech.edu //The data format used by the zlib library is described by RFCs (Request for //Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt //(zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).