0

When I open a file in binary mode, does a situation exist where is_open() is true but good() is false ?

bool ok = false;
std::ifstream stream("test.dat", std::ios::binary)
if (stream.is_open())
{
    ok = stream.good();//Does a situation exist where the result of this is false ?
    stream.close();
}
Vincent
  • 57,703
  • 61
  • 205
  • 388
  • I think if the file is empty, `good()` may return false, but it is not guaranteed to until the first read attempt. – Praetorian Oct 08 '12 at 02:11
  • No, but any i/o operation after the is_open() call could set the bad, fail or eof bits. – imreal Oct 08 '12 at 02:15
  • 1
    @Prætorian if the file is empty, the eof bit wont be set unitl an i/o operation is performed. – imreal Oct 08 '12 at 02:16

1 Answers1

1

No: the two-argument constructor of std::ifstream is required to set the failbit if file opening fails.

§27.9.1.7[ifstream.cons]/2

explicit basic_ifstream(const char* s, ios_base::openmode mode = ios_base::in);

calls rdbuf()->open(s, mode | ios_base::in). If that function returns a null pointer, calls setstate(failbit).

and, for open(),

§27.9.1.4[filebuf.members]/2

basic_filebuf<charT,traits>* open(const char* s, ios_base::openmode mode);

Returns: this if successful, a null pointer otherwise

Community
  • 1
  • 1
Cubbi
  • 46,567
  • 13
  • 103
  • 169