Unexpected results with std::ofstream binary write

前端 未结 2 1059
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 14:25

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\         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 14:55

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

提交回复
热议问题