It is a well known method to copy a stream into another using rdbuf
:
#include <iostream>
#include <fstream>
int main()
{
std::ifstream in{"/tmp/foo.txt"};
std::cerr << in.rdbuf();
std::cerr << "Done\n";
}
However, this breaks (= sets the bad bit) my cerr
when /tmp/foo.txt
is empty. As a result, Done\n
is not displayed.
Why is that? Observed with G++/libstdc++/GNU Linux and Clang++/libc++/OS X.
That seems to be the defined behaviour - see e.g. http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt:
If no characters were inserted, executes setstate(failbit)
I agree it's a bit unhelpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With