std::ios_base::failbit and output streams

Feb 19, 2013 at 6:38pm
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.
Feb 19, 2013 at 7:28pm
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.
Feb 19, 2013 at 7:35pm
> 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 Feb 19, 2013 at 7:42pm
Feb 19, 2013 at 8:39pm
@ 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?"
Feb 20, 2013 at 3:43am
@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> )
Feb 20, 2013 at 8:23am
> "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 Feb 20, 2013 at 10:09am
Topic archived. No new replies allowed.