C++ 将数据写出压缩文件
时间: 2024-02-21 14:57:55 浏览: 177
要将数据写入压缩文件,可以使用zlib库中提供的函数。下面是一个简单的示例,展示如何使用C++编写数据并将其压缩并写入文件中:
```cpp
#include <iostream>
#include <fstream>
#include <zlib.h>
const int CHUNK_SIZE = 16384; // 压缩块大小
void compressData(const char* data, size_t dataSize, const std::string& fileName)
{
std::ofstream outFile(fileName, std::ios::out | std::ios::binary);
if (!outFile.is_open())
{
std::cerr << "Error: Failed to open file " << fileName << " for writing!" << std::endl;
return;
}
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = (uInt)dataSize;
stream.next_in = (Bytef*)data;
if (deflateInit(&stream, Z_DEFAULT_COMPRESSION) != Z_OK)
{
std::cerr << "Error: Failed to initialize compression stream!" << std::endl;
return;
}
int ret;
char outBuffer[CHUNK_SIZE];
do
{
stream.avail_out = CHUNK_SIZE;
stream.next_out = (Bytef*)outBuffer;
ret = deflate(&stream, Z_FINISH);
if (outFile.fail())
{
std::cerr << "Error: Failed to write compressed data to file!" << std::endl;
deflateEnd(&stream);
return;
}
size_t compressedSize = CHUNK_SIZE - stream.avail_out;
outFile.write(outBuffer, compressedSize);
} while (stream.avail_out == 0);
deflateEnd(&stream);
outFile.close();
std::cout << "Data compressed and written to file " << fileName << std::endl;
}
```
在上面的示例中,我们使用了zlib库中的`deflate()`函数将数据压缩,并使用`deflateInit()`和`deflateEnd()`函数初始化和结束压缩流。我们使用`std::ofstream`类将压缩后的数据写入文件中。
需要注意的是,压缩后的数据是以二进制格式写入文件的,因此在读取时也需要以二进制格式进行读取。
阅读全文
相关推荐















