如何将bitset数据写入文件? [英] How to write bitset data to a file?

查看:1042
本文介绍了如何将bitset数据写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std :: bitset,我想写入一个文件,位为位,但当然fstream的写函数不支持这一点。我不能想到另一种方式,除了将每个8位组转换为使用字符串和写的字符...

I have a std::bitset that I'd like to write to a file, bit for bit, but of course fstream's write function doesn't support this. I can't think of another way besides converting each 8-bit group to a char using string and writing that...

任何人都知道一个好的方法? p>

Anyone know of a good way?

推荐答案

尝试:

#include <bitset>
#include <fstream>

int main() {
    using namespace std;
    const bitset<12> x(2730ul); 
    cout << "x =      " << x << endl;

    ofstream ofs("C:\\test.txt"); // write as txt
    if (ofs) {
        // easy way, use the stream insertion operator
        ofs << x << endl;

        // using fstream::write()
        string s = x.to_string();
        ofs.write(s.c_str(), s.length()); 
    }
    return 0;
}

这篇关于如何将bitset数据写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆