34

私は 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.txticf10c30.4

私が間違っていることを教えてください。

4

2 に答える 2

18

std::ios::binaryストリームで行末変換を行わないことを約束します (およびテキスト ストリームとのその他の小さな動作の違い)。

あなたは見ることができます

Boost Spirit Karma を使用した例を次に示します (ビッグエンディアンのバイト順を想定):

#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 
于 2013-02-08T07:44:42.707 に答える
16

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();
}
于 2013-02-08T07:55:35.557 に答える