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

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

问题描述

我在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 的作用是防止诸如将'\ n'从特定平台的EOL转换到特定平台的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.)

要实际写入二进制对象,请使用 std :: ostream :: write().但是要注意,结果是特定于平台的.

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

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

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