C语言压缩字符串保存到二进制文件,从二进制文件读取压缩字符串后解压。

  1. 在vcpkg的环境下,确认已安装boost库

  2. 在Debug,x64环境下附加依赖项:
    在这里插入图片描述
    在这里插入图片描述

  3. 切换到Release,x64环境,并附加依赖项:
    在这里插入图片描述
    附加依赖项以后点击应用,程序跑起来就不会编译不通过。

  4. 编写代码:

#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;
}
  1. 运行结果
    在这里插入图片描述
    查看a.bin文件,这是我随便从键盘输入的内容:
    在这里插入图片描述
    查看b.bin文件,这是压缩后的内容,在终端输出查看是乱码来的
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值