c++ - 如何将字符串保存为二进制文件

标签 c++

这是我的代码

    bool saveFile (string name, string contents)
{
    ofstream file;
    file.open(name.c_str(), ios::binary);
    file.write(contents.c_str(),contents.size());
    file.close();

}

确定编辑:

我的字符串包含

10100101111111110000

当我将其保存为二进制文件并使用记事本打开时,我希望看到 ascii 表中的随机字符,但我看到的是完全相同的 0 和 1 流

最佳答案

如果您有一个“二进制”文本字符串 '1''0'字符,您可以使用 std::bitset<8> 将其编码为字节.

void saveFile (std::string name, std::string contents) {
    std::ofstream file(name.c_str(), std::ios::binary);
    for ( std::size_t byte = 0; byte < contents.size(); byte += 8 ) {
        file.put( std::bitset< 8 >( contents, byte, // convert one byte
          std::min( (std::size_t) 8, contents.size() - byte ) // or as many bits as are left
          .to_ulong() ); // to two's complement representation
    }
}

关于c++ - 如何将字符串保存为二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17131902/

相关文章:

c++ - 条件运算符和数组/返回指向数组的指针

c++ - 从 C++ 访问表中的 Lua 表

c++ - 从数组中删除并移动

c++ - 在开源项目中存储 OAuth secret

c++ - 使用 operator new 从 C 实例化 C++ 对象

c++ - 在 C++ 上获取对 Perl 的 undefined reference

c++ - 如何选择调用的重载函数

c++ - 将大量数据从 FORTRAN 传递到 C++

C++、MinGW、Windows:使用 std::cout 打印数字非常慢

c++ - 提升图形库 : Error while compiling with make_reverse_graph