Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::cout set badbit or failbit with the operator <<? If so, when?

Tags:

c++

c++11

Can std::cout set the badbit or failbit with the operator <<. If so, when does this occur?

like image 855
wyer33 Avatar asked Jan 09 '23 16:01

wyer33


1 Answers

std::cout maps to lower-level OS facilities, and anything that could make the OS fail its write will show up as failbit or badbit. For example, on Linux, you can cause this to happen by closing stdout:

int main(int argc, char* argv[])
{
  close(1);
  std::cout << "Hello, world!" << std::endl;
  return cout.fail(); // returns 1
}

(And, because file descriptors are inherited, your calling process may have closed stdout for you.)

like image 77
Josh Kelley Avatar answered Jan 26 '23 21:01

Josh Kelley