Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 961
akim Avatar asked Nov 20 '15 14:11

akim


1 Answers

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.

like image 65
Alan Stokes Avatar answered Nov 04 '22 00:11

Alan Stokes