When you try to read a file that is open for output only, the eofbit flag is set on the stream. Why is this?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream file("out.txt", ios_base::app);

    file.seekg(0, ios_base::beg);

    char buffer[100];

    if( !file.getline(buffer, 99) )
        cout << "file.failbit  " << boolalpha << file.fail() << "   file.eofbit   " << file.eof()
                 << '\n'
             << "file.badbit   " << file.bad() << "  file.goodbit  " << file.good() << '\n';

}

      

Output

enter image description here

+3


source to share


1 answer


The standard prohibits you from reading from an output-only file. From clause 27.9.1.1.3 to basic_filebuf

(part of the base implementation fstream

):

If the file is not open for reading, the input sequence cannot be read.



Therefore, when trying to read from a write-only file, expect failbit

. The standard also says that it is eofbit

set when it getline

reaches the end of the input sequence. Since you actually have an empty input sequence (i.e. a File that you cannot read), the first call to getline sets eofbit

. In the standard standard stream buffer below... basic_streambuf::underflow()

returns traits::eof()

on failure (see 27.6.3.4.3, clauses 7-17).

To fix this add ios_base::in

openmode.

+2


source







All Articles