使用 rdbuf
将流复制到另一个流是一种众所周知的方法:
#include <iostream>
#include <fstream>
int main()
{
std::ifstream in{"/tmp/foo.txt"};
std::cerr << in.rdbuf();
std::cerr << "Done\n";
}
但是,当 /tmp/foo.txt
为空时,这会破坏(= 设置错误位)我的 cerr
。因此,不会显示 Done\n
。
这是为什么呢?使用 G++/libstdc++/GNU Linux 和 Clang++/libc++/OS X 观察。
最佳答案
这似乎是定义的行为 - 参见例如http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt :
If no characters were inserted, executes setstate(failbit)
我同意这有点没用。
关于c++ - 使用 rdbuf 复制流在输入为空时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33829403/