我是 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
的二进制表示, c
和 f
, 但我有 10c30.4
.
你能告诉我我做错了什么吗?
最佳答案
std::ios::binary
promise 不会对流进行任何行尾转换(以及与文本流的一些其他小行为差异)。
你可以看看
- 促进序列化 http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/index.html
- Boost Spirit 二进制生成器 http://www.boost.org/doc/libs/1_53_0/libs/spirit/doc/html/spirit/karma/reference/binary/
- 使用 ofstream::write(...) 手动写入字节
这是一个使用 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/