-
在vcpkg的环境下,确认已安装boost库
-
在Debug,x64环境下附加依赖项:
-
切换到Release,x64环境,并附加依赖项:
附加依赖项以后点击应用,程序跑起来就不会编译不通过。 -
编写代码:
#include <iostream>
#include <sstream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <stdio.h>
#include <string>
using namespace std;
std::string compress(const std::string& data) {
namespace bio = boost::iostreams;
std::stringstream compressed;
std::stringstream origin(data);
bio::filtering_streambuf<bio::input> out;
out.push(bio::gzip_compressor(bio::gzip_params(bio::gzip::best_speed)));
out.push(origin);
bio::copy(out, compressed);
return compressed.str();
}
std::string decompress(const std::string& data)
{
namespace bio = boost::iostreams;
std::stringstream compressed(data);
std::stringstream decompressed;
bio::filtering_streambuf<bio::input> out;
out.push(bio::gzip_decompressor());
out.push(compressed);
bio::copy(out, decompressed);
return decompressed.str();
}
int main() {
// 先在a.bin文件手动输入一些字符串
//以二进制形式读取a.bin文件
FILE* raf = fopen("../static/a.bin", "rb");
char bufa;
string astr = "";
while (true) {
bufa = fgetc(raf);
if (feof(raf) != 1) {
astr += bufa;
}
else {
break;
}
}
fclose(raf);
//以二进制形式写入b.bin文件,并将从a.bin文件读取的字符串压缩后写入到b.bin文件
FILE* wbf = fopen("../static/b.bin", "wb");
string bstr = compress(astr);
for (int i = 0; i < bstr.size(); i++) {
fputc(bstr[i], wbf);
}
fclose(wbf);
//以二进制形式读取b.bin文件
FILE* rbf = fopen("../static/b.bin", "rb");
string readbstr = "";
char bufb;
while (true) {
bufb = fgetc(rbf);
if (feof(rbf) != 1) {
readbstr += bufb;
}
else {
break;
}
}
fclose(rbf);
//检查从bin文件读取的字符串和使用compress函数压缩的字符串是否相同。
//如果不采用二进制读取,直接读取的话,两者可能会不相同。
if (bstr == readbstr) {
cout << "same....." << endl;
}
//读取压缩的二进制文件并解压读取。
cout << "读取的压缩字符串::" << readbstr << endl;
cout << "decompressing..." << endl;
string decmpstr = decompress(readbstr);
cout << "解压后的字符串::" << decmpstr << endl;
return 0;
}
- 运行结果
查看a.bin文件,这是我随便从键盘输入的内容:
查看b.bin文件,这是压缩后的内容,在终端输出查看是乱码来的