无法写入二进制文件 [英] Can't write a binary file

查看:156
本文介绍了无法写入二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中有下面的代码片段。

I have the following piece of code in C++.

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ofstream output("Sample.txt", ios::out | ios::binary);

for(int i = 0; i < 10; i++)
{
  output<<arr[i];
}



现在Sample.txt类似这样:

Now the Sample.txt is like this:

12345678910

Sample.txt应该是二进制?为什么当我以二进制模式打开流时,它不会将一切转换为二进制。我应该怎么做,我需要数组中每个元素的二进制,然后打印到文件。

Isn't the "Sample.txt" supposed to be in binary? Why doesn't it convert everything into binary when i opened the stream in binary mode. What should I do, incase i need binary of every element in the array and then print it to the file.

推荐答案


不是Sample.txt应该是二进制的?

Isn't the "Sample.txt" supposed to be in binary?

否。 std :: ios :: binary 的作用是防止类似于'\\\
'
到平台特定的EOL。它不会跳过数据字节的内部表示和字符串转换之间的转换。毕竟,这就是流是什么。 (另外,想一想如何流式传输包含二进制表示形式的指针的用户定义类型的对象。)

No. What std::ios::binary does is to prevent things like the translation of '\n' from/to the platform-specific EOL. It will not skip the translation between the internal representation of the data bytes and their string translation. After all, that's what streams are all about. (Also, think of how you would stream an object of a user-defined type containing pointers in a binary representation.)

实际写入对象binary use std :: ostream :: write()。当心,但结果是平台特定。

To actually write objects binary use std::ostream::write(). Beware, though, the result is platform-specific.

这篇关于无法写入二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆