使用std :: ofstream二进制写的意外结果 [英] Unexpected results with std::ofstream binary write

查看:468
本文介绍了使用std :: ofstream二进制写的意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接触C ++ std :: stream,我正在做一些测试。我有这个简单的代码:

I'm new to C++ std::stream and I'm making some tests. I have this simple code:

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 c f ,但是我有 10c30.4

As the stream is opened as std::ios::binary I expect in the test.txt file to have the binary representation of i, c and f, but instead I have 10c30.4.

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

Can you please tell me what I'm doing wrong?

推荐答案

std :: ios :: binary

您可以查看

这里有一个使用Boost Spirit Karma的例子(假设Big-Endian字节排序):

Here's an example using Boost Spirit Karma (assuming Big-Endian byte ordering):

#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 

这篇关于使用std :: ofstream二进制写的意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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