std::ios_base::failbit and output streams

Does it make sense to set std::ios_base::failbit to throw exceptions, for output streams? As in:

1
2
3
4
5
std::ofstream output_file("out.txt");

output_file.exceptions(std::ios_base::badbit | std::ios_base::failbit);

// ... 


I ask because the fail bit seems to be exclusively about input conversion errors.
There are very few failure conditions on output streams that set failbit. The easiest to test, specifically for the output file streams that you are showing, is double-close.
> I ask because the fail bit seems to be exclusively about input conversion errors.

GCC has a fairly long way to go before libstdc++ streams and locales become conforming.

A conforming implementation would set the fail bit on an output stream if the output operations fail.
http://liveworkspace.org/code/22lLbD$0

If the implementation refuses to set the fail bit, I don't see how it can throw either.

EDIT: Just checked it; gcc too sets the fail bit if it is on on Linux http://liveworkspace.org/code/22lLbD$2
Last edited on
@ Cubbi: thanks. Which are the other cases?

@ JLBorges: thanks, but I'd rephrase my question as: "when is the fail bit set for output streams, but the bad bit isn't?"
@Catfish3
Another example: outputting an empty streambuf into your stream:
1
2
3
4
5
6
7
8
9
10
#include <fstream>
#include <iostream>

int main()
{
    std::ifstream i;
    std::ofstream f("test.txt");
    f << i.rdbuf();
    std::cout << "eof: " << f.eof() << " fail: " << f.fail() << " bad: " << f.bad() << '\n';
}


@JLBorges
LWS's default options for clang++ select GNU stdlibc++ as the library (try to #include <codecvt> )
> "when is the fail bit set for output streams, but the bad bit isn't?"

In cases where the ouput operation has failed, but if we clear the failed state and try another correct output operation, it is likely to succeed. For instance,
Cubbi's example above.

> LWS's default options for clang++ select GNU stdlibc++ as the library

Thanks; didn't know that.

EDIT: Alas, -stdlib=libc++ is not supported by LWS.
l
Last edited on
Topic archived. No new replies allowed.