akim
akim

Reputation: 8769

Copy streams using rdbuf fails on empty input

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.

Upvotes: 6

Views: 552

Answers (1)

Alan Stokes
Alan Stokes

Reputation: 18974

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.

Upvotes: 5

Related Questions