Copying streams using rdbuf fails with empty input

This is a well-known method for copying a stream to 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 aborts (= sets the bad bit) my cerrwhen /tmp/foo.txtempty. The result is Done\nnot displayed.

Why? Observed with g ++ / libstdC ++ / GNU Linux and Clang ++ / libC ++ / OS X.

+4
source share
1 answer

This is apparently a specific behavior - see, for example, http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt :

If no characters were inserted, setstate (failbit) is executed

I agree with this a little useless.

+3

Source: https://habr.com/ru/post/1616752/


All Articles