c++ - While trying to read a file opened for output only, the eofbit flag is set for the stream. Why is that? -
c++ - While trying to read a file opened for output only, the eofbit flag is set for the stream. Why is that? -
#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
the standard prohibits reading file opened output. paragraph 27.9.1.1.3 on basic_filebuf
(part of underlying implementation of fstream
):
if file not open reading input sequence cannot read.
one hence expect see failbit
when trying read file open writing. standard says eofbit
set whenever getline
reaches end of input sequence. since have empty input sequence (i.e., file can't read from), first phone call getline sets eofbit
well. in standardese, underlying stream buffer underflows. basic_streambuf::underflow()
returns traits::eof()
on failure (see 27.6.3.4.3 paragraphs 7-17).
to prepare this, add together ios_base::in
file's openmode.
c++ fstream
Comments
Post a Comment