gpt4 book ai didi

c++ - std::ofstream 二进制写入的意外结果

转载 作者:IT老高 更新时间:2023-10-28 12:41:50 24 4
gpt4 key购买 nike

我是 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 的二进制表示, cf ,但我有 10c30.4 .

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

最佳答案

std::ios::binary promise 不对流进行任何行尾转换(以及与文本流的一些其他小的行为差异)。

你可以看看

这是一个使用 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/14767857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com