栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

  2. 在Debug,x64环境下附加依赖项:

  3. 切换到Release,x64环境,并附加依赖项:

    附加依赖项以后点击应用,程序跑起来就不会编译不通过。

  4. 编写代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

std::string compress(const std::string& data) {
    namespace bio = boost::iostreams;

    std::stringstream compressed;
    std::stringstream origin(data);

    bio::filtering_streambuf 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 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文件,这是压缩后的内容,在终端输出查看是乱码来的
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/960147.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号