我总是阅读并被告知,在处理二进制文件时,应该使用 read() 和 write() 而不是 << 和>> 运算符,因为它们适用于格式化数据。 我还读到可以使用它们,但这是一个高级主题,我找不到有人深入研究和讨论的地方。
我最近看到一些代码执行以下操作:
std::ifstream file1("x", ios_base::in | ios_base::binary);
std::ofstream file2("y", ios_base::app | ios_base::binary);
file1 << file2.rdbuf();
当我指出 << 的使用时, 运算符与二进制文件,我被告知 rdbuf() 调用返回一个 Streambuf * 并且 << 重载streambuf*并进行不带格式的直接复制,因此是安全的。
这是真的并且安全吗? 效率如何? 有什么问题吗? 详细信息将不胜感激。
谢谢!
I've always read and been told that when dealing with binary files that one should use read() and write() as opposed to the << and >> operators as they are meant for use with formatted data. I've also read that it is possible to use them, but it is an advanced topic, which I can't find where anyone dives into and discusses.
I recently saw some code which did the following:
std::ifstream file1("x", ios_base::in | ios_base::binary);
std::ofstream file2("y", ios_base::app | ios_base::binary);
file1 << file2.rdbuf();
When I pointed out the use of the << operator with the binary file, I was told that the rdbuf() call returns a streambuf * and that << overloads the streambuf* and does a direct copy with no formatting and is thus safe.
Is this true and also safe? How about efficiency? Any gotchas? Details would be much appreciated.
Thanks!
发布评论
评论(3)
是(参见 27.6.2.5.3/6,其中描述了 Streambuf 的 << 重载)。
Yes (see 27.6.2.5.3/6 where the overload of << for streambuf is described).
这是完全安全且合理的复制流的方法。
请注意,它还允许以下内容:
It's entirely safe and a reasonable way to copy streams.
Note that it also allows stuff like:
在 C++ 标准的第 27.7.3.6.3 节中,提到了
basic_ostream& 运算符<<* sb);
(basic_streambuf
效果:表现为未格式化的输出函数(如 27.7.3.7 第 1 段中所述)。
§ 27.7.3.7 描述了“未格式化的输入”,它基本上是一个二进制副本。 这意味着“未格式化”的 ostream 函数对于二进制数据是安全的。 我能找到的标准中提到的其他“未格式化”函数有
put
、write
和(官方)flush
。In § 27.7.3.6.3 of the C++ standard, it's mentioned that
basic_ostream<charT,traits>& operator<<
(basic_streambuf<charT,traits>* sb);
Effects: Behaves as an unformatted output function (as described in 27.7.3.7, paragraph 1).
§ 27.7.3.7 describes "unformatted input" which is basically a binary copy. This means that "unformatted" ostream functions are safe for binary data. The other "unformatted" functions mentioned in the standard that I can find are
put
,write
and (officially)flush
.