Unexpected results with std::ofstream binary write

自闭症网瘾萝莉.ら 提交于 2019-11-27 07:43:08

问题


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();
}

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?


回答1:


std::ios::binary promises to not do any line-end conversions on the stream (and some other small behavioral differences with text streams).

You could look at

  • Boost Serialization http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/index.html
  • Boost Spirit binary generators http://www.boost.org/doc/libs/1_53_0/libs/spirit/doc/html/spirit/karma/reference/binary/
  • Using ofstream::write(...) to manually write the bytes

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";
}

This prints

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



回答2:


In order to write raw binary data you have to use ostream::write. It does not work with the output operators.

Also make sure if you want to read from a binary file not to use operator>> but instead istream::read.

The links also provide examples how you can handle binary data.

So for your example:

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.write(reinterpret_cast<const char*>(&i), sizeof(i));
    out.write(&c, sizeof(c));
    out.write(reinterpret_cast<const char*>(&f), sizeof(f));
    out.close();
}


来源:https://stackoverflow.com/questions/14767857/unexpected-results-with-stdofstream-binary-write

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!