Can std :: cout set badbit or failbit with << operator? If yes, then when?

Can be std::cout

installed badbit

or failbit

by operator <<

. If so, when does this happen?

+3


source share


2 answers


std::cout

displays lower-level OS objects, and anything that can cause the OS to crash will be displayed as failbit

or badbit

. For example, on Linux, you can call this by closing stdout:

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

      



(And since file descriptors are inherited, your calling process may have a private stdout for you.)

+4


source


Can be std::cout

installed badbit

or failbit

by operator <<

. If so, when does this happen?

In general (not only std::cout

), these are the reasons why output operations can fail ( as from cppreference.com ):



Badbit is set by the following standard library functions:

  • basic_ostream::put

    if it cannot insert a character into the output of the stream for any reason.
  • basic_ostream::write

    if it can't insert for some reason.
  • The formatted output of the function operator<<

    , std::put_money

    and std::put_time

    if they encountered the end of the output stream before completing the output.

.....

The crash failure is set by the following standard library functions:

  • basic_ostream::tellp

    on failure
  • Constructors std::basic_fstream

    , std::basic_ifstream

    and std::basic_ofstream

    , which takes a filename argument if the file cannot be opened.
  • basic_fstream::open

    , basic_ifstream::open

    And basic_ofstream::open

    if the file does not open.
  • basic_fstream::close

    basic_ifstream::close

    and basic_ofstream::close

    if the file cannot be closed.
+3


source







All Articles