c++ - std::ofstream 二进制写入的意外结果

标签 c++ iostream

我是 C++ std::stream 的新手,我正在做一些测试。我有这个简单的代码:

int i = 10;
char c = 'c';
float f = 30.40f;

std::ofstream out("test.txt", std::ios::binary | std::ios::out);
if(out.is_open())
{
    out<<i<<c<<f;
    out.close();
}

因为流被打开为 std::ios::binary我希望在 test.txt文件具有 i 的二进制表示, cf , 但我有 10c30.4 .

你能告诉我我做错了什么吗?

最佳答案

std::ios::binary promise 不会对流进行任何行尾转换(以及与文本流的一些其他小行为差异)。

你可以看看

这是一个使用 Boost Spirit Karma 的示例(假设字节顺序为 Big-Endian):

#include <boost/spirit/include/karma.hpp>
namespace karma = boost::spirit::karma;

int main()
{
    int i = 10;
    char c = 'c';
    float f = 30.40f;

    std::ostringstream oss(std::ios::binary);
    oss << karma::format(
            karma::big_dword << karma::big_word << karma::big_bin_float, 
            i, c, f);

    for (auto ch : oss.str())
        std::cout << std::hex << "0x" << (int) (unsigned char) ch << " ";
    std::cout << "\n";
}

这打印

0x0 0x0 0x0 0xa 0x0 0x63 0x41 0xf3 0x33 0x33 

关于c++ - std::ofstream 二进制写入的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25411199/

相关文章:

c++ - IEnumString::Next 的资源管理契约是什么?

c++ - "std::endl"与 "\n"

java - 如何在Java中读取.EXE文件的内容

c++ - 尝试内联函数时 Visual C++ 中的链接错误

从 Boost object_pool 构造的指针的 C++ Boost 二进制序列化

c++ - 从 iostream 读取父类(super class)的子类实例。 >> 运算符如何知道哪个子类?

c++ - 为什么从 std::istream 读取记录结构字段失败,我该如何解决?

C++ 缩进重载 ostream 运算符

gcc 4.4.7 : base class subobject padding occupied in derived class object 的 C++ 对象模型

c++ - 如何使用用户输入制作字符串队列?