Can std :: cout set badbit or failbit with << operator? If yes, then when?
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.)
source share
Can be
std::cout
installedbadbit
orfailbit
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
andstd::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
andstd::basic_ofstream
, which takes a filename argument if the file cannot be opened.basic_fstream::open
,basic_ifstream::open
Andbasic_ofstream::open
if the file does not open.basic_fstream::close
basic_ifstream::close
andbasic_ofstream::close
if the file cannot be closed.
source share