3
votes

I could not find pretty much any information on this. Whether and if so, under what circumstances, can eofbit be set (meaning ofstream_instance.eof() is true )?

I am more interested in an independent ofstream, one that is not associated with an ifstream within some fstream, so that the "shared" eofbit can't be set by the ifstream (if something like that is possible).

If I simply write to a file and there is no space on disk or operation system does not provide another space for the writing, then I'd expect just only either failbit or badbit to be set, but reaching end of file while writing to it does not make sense to me. However no discussion on this I was able to find.

1
I still don't get why it should be necessary to set eof bit in std::ofstream. If you close() the std::ofsteam and it doesn't fail I would assume that output was successfully. Though, I somewhere read that this is true "above" OS level only. To grant this for the harddisk may take even more effort (beyond std C++) e.g. doing an fsync(). (My stomache was right - found:) SO: How do I ensure data is written to disk before closing fstream?Scheff's Cat

1 Answers

5
votes

No. eof() returns the eofbit, which has no real meaning for an output stream with no associated input stream.

eofbit indicates that an input operation reached the end of an input sequence

[ios.types] / 3.1, Table 107

The actions that set eofbit are enumerated here, and they all act on input streams only.

We could imagine some weird implementation-specific scenario in which EOF (as opposed to some other error condition) would be hit while writing to a file - maybe there is a fixed-size file buffer we are writing to through some OS functions - but as far as I know the standard library abstractions do not deal with that case, and I have never seen or heard of such an API in the first place.