aki*_*kim 6 c++ stream ostream
使用rdbuf以下方法将流复制到另一个流中是一种众所周知的方法:
#include <iostream>
#include <fstream>
int main()
{
std::ifstream in{"/tmp/foo.txt"};
std::cerr << in.rdbuf();
std::cerr << "Done\n";
}
Run Code Online (Sandbox Code Playgroud)
但是,这会中断(= 设置坏位) my cerrwhen/tmp/foo.txt为空。结果,Done\n不显示。
这是为什么?使用 G++/libstdc++/GNU Linux 和 Clang++/libc++/OS X 观察。
这似乎是定义的行为 - 参见例如http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt:
如果没有插入字符,则执行 setstate(failbit)
我同意这有点无益。