我是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();
}
Run Code Online (Sandbox Code Playgroud)
正如std::ios::binary
我在test.txt
文件中所期望的那样打开流以具有二进制表示形式i
,c
并且f
,但是我有10c30.4
.
你能告诉我我做错了什么吗?
seh*_*ehe 17
std::ios::binary
承诺不对流进行任何行结束转换(以及与文本流的一些其他小行为差异).
你可以看看
这是使用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";
}
Run Code Online (Sandbox Code Playgroud)
这打印
0x0 0x0 0x0 0xa 0x0 0x63 0x41 0xf3 0x33 0x33
Run Code Online (Sandbox Code Playgroud)
mis*_*ink 13
为了编写原始二进制数据,您必须使用ostream :: write.它不适用于输出运算符.
还要确保是否要从二进制文件中读取不使用operator >>而是使用istream :: read.
这些链接还提供了如何处理二进制数据的示例.
所以对于你的例子:
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();
}
Run Code Online (Sandbox Code Playgroud)