[英]C++ fstream << and >> operators with binary data
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. 我总是阅读并被告知,在处理二进制文件时,应该使用read()和write()而不是<<和>>运算符,因为它们用于格式化数据。 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. 当我指出使用<<运算符和二进制文件时,我被告知rdbuf()调用返回一个streambuf *并且<<重载streambuf *并执行没有格式化的直接复制,因此是安全的。
Is this true and also safe? 这是真的还安全吗? How about efficiency?
效率怎么样? Any gotchas?
任何陷阱? Details would be much appreciated.
细节将不胜感激。
Thanks! 谢谢!
是(见27.6.2.5.3 / 6,其中描述了<< for streambuf的重载)。
It's entirely safe and a reasonable way to copy streams. 它是完全安全的,也是复制流的合理方式。
Note that it also allows stuff like: 请注意,它还允许以下内容:
std::ifstream file_in1("x1", ios_base::in | ios_base::binary);
std::ifstream file_in2("x2", ios_base::in | ios_base::binary);
std::ofstream file_out("y", ios_base::app | ios_base::binary);
file_out << file_in1.rdbuf() << "\nand\n" << file_in2.rdbuf();
In § 27.7.3.6.3 of the C++ standard, it's mentioned that 在C ++标准的第27.7.3.6.3节中,提到了这一点
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. §27.7.3.7描述了“无格式输入”,它基本上是一个二进制副本。 This means that "unformatted" ostream functions are safe for binary data.
这意味着“未格式化”的ostream函数对于二进制数据是安全的。 The other "unformatted" functions mentioned in the standard that I can find are
put
, write
and (officially) flush
. 我能找到的标准中提到的其他“无格式”功能是
put
, write
和(正式) flush
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.