[英]What does outputting the filebuf* of an ofstream in C++ do?
使用ifstream
我们可以将整个文件输出到cout
如下所示:
std::ifstream foo("testfile");
std::cout << foo.rdbuf();
但是,当我们尝试对ofstream
进行相同操作时会发生什么?
std::ofstream foo("testfile", std::ios::app); // use app to avoid wiping out contents of testfile
std::cout << foo.rdbuf();
对我来说,它什么都不输出。
是否将ofstream
的filebuf*
传递给std::cout::operator<<
只是没有实际用途的无用可能性? 还是有我不知道的东西?
当执行operator <<
作为未格式化数据插入streambuf
重载时,将流缓冲区拉到达到eof为止,但是没有什么可以开始的,所以...
结果是将写入零个字符。 根据标准(C ++ 14§27.7.3.6.3 / 9),在这种情况下,它在目标输出流上设置的故障位由以下内容证明:
#include <iostream>
#include <fstream>
#include <iomanip>
int main()
{
std::ofstream foo("testfile", std::ios::app);
std::cerr << std::boolalpha << std::cout.fail() << '\n';
std::cout << foo.rdbuf();
std::cerr << std::boolalpha << std::cout.fail() << '\n';
}
输出量
false
true
是的,在这种情况下,它不仅是无用的,而且还会使目标ostream
失效,直到其ostream
-state)被clear()
。
祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.