linux c++ 压缩 zip
时间: 2023-11-14 19:09:33 浏览: 167
zip文件解压(C++)
您可以使用 zlib 库来进行压缩和解压缩操作。zlib 是一个开源的压缩库,支持多种压缩算法,包括 deflate、gzip 和 zlib 等。在 Linux 系统中,您可以使用以下命令安装 zlib 库:
```
sudo apt-get install zlib1g-dev
```
然后,您可以使用以下代码来进行压缩和解压缩操作:
```c++
#include <iostream>
#include <fstream>
#include <cstring>
#include <zlib.h>
using namespace std;
// 压缩函数
bool compressFile(const char* srcFile, const char* dstFile)
{
ifstream fin(srcFile, ios::binary);
if (!fin)
{
cout << "Failed to open source file!" << endl;
return false;
}
ofstream fout(dstFile, ios::binary);
if (!fout)
{
cout << "Failed to create destination file!" << endl;
return false;
}
// 初始化 zlib
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK)
{
cout << "Failed to initialize zlib!" << endl;
return false;
}
// 压缩数据
char buffer[1024];
while (!fin.eof())
{
fin.read(buffer, sizeof(buffer));
zs.avail_in = fin.gcount();
zs.next_in = reinterpret_cast<Bytef*>(buffer);
do
{
zs.avail_out = sizeof(buffer);
zs.next_out = reinterpret_cast<Bytef*>(buffer);
if (deflate(&zs, Z_FINISH) == Z_STREAM_ERROR)
{
cout << "Failed to compress data!" << endl;
deflateEnd(&zs);
return false;
}
fout.write(buffer, sizeof(buffer) - zs.avail_out);
} while (zs.avail_out == 0);
}
// 结束压缩
deflateEnd(&zs);
fin.close();
fout.close();
return true;
}
// 解压缩函数
bool decompressFile(const char* srcFile, const char* dstFile)
{
ifstream fin(srcFile, ios::binary);
if (!fin)
{
cout << "Failed to open source file! << endl;
return false;
}
ofstream fout(dstFile, ios::binary);
if (!fout)
{
cout << "Failed to create destination file!" << endl;
return false;
}
// 初始化 zlib
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (inflateInit(&zs) != Z_OK)
{
cout << "Failed to initialize zlib!" << endl;
return false;
}
// 解压数据
char buffer[1024];
while (!fin.eof())
{
fin.read(buffer, sizeof(buffer));
zs.avail_in = fin.gcount();
zs.next_in = reinterpret_cast<Bytef*>(buffer);
do
{
zs.avail_out = sizeof(buffer);
zs.next_out = reinterpret_cast<Bytef*>(buffer);
if (inflate(&zs, Z_NO_FLUSH) == Z_STREAM_ERROR)
{
cout << "Failed to decompress data!" << endl;
inflateEnd(&zs);
return false;
}
fout.write(buffer, sizeof(buffer) - zs.avail_out);
} while (zs.avail_out == 0);
}
// 结束解压
inflateEnd(&zs);
fin.close();
fout.close();
return true;
}
int main()
{
const char* srcFile = "test.txt";
const char* zipFile = "test.zip";
const char* dstFile = "test_copy.txt";
// 压缩文件
if (compressFile(srcFile, zipFile))
{
cout << "Compress file success!" << endl;
}
else
{
cout << "Compress file failed!" << endl;
return -1;
}
// 解压文件
if (decompressFile(zipFile, dstFile))
{
cout << "Decompress file success!" << endl;
}
else
{
cout << "Decompress file failed!" << endl;
return -1;
}
return 0;
}
```
阅读全文