right way check file open and end

  • check if a state is ok

while(cin >> word)
// ok: read successful

  • condition states are constants defined in ios_base as public members

    • ios_base::badbit : corrupted.
      • set when the error involves the loss of integrity of the stream, which is likely to persist even if a different operation is attempted on the stream.
      • indicates a system-level failure, such as an unrecoverable read or write error.
      • usually not possible to use a stream once badbit has been set.
    • ios_base::failbit : failed.
      • set by an operation when the error is related to the internal logic of the operation itself; further operations on the stream may be possible.
      • is set after a recoverable error, such as reading a character when numeric data was expected.
      • often possible to correct such problems and continue using the stream.
    • ios_base::eofbit : hit end-of-file.
    • ios_base::goodbit : not in an error state.
      • indicating none of the other bits is set.
  • Note

    • At least one of failbit and badbit is set when an error occured during an input operation.
    • Failing to read due to reaching the end-of-file sets both eofbit and failbit.
    • fail() is a synonym of ios::operator!
  • checks

    • s.bad() : eofbit is set.
    • s.fail() : failbit or badbit is set.
    • s.eof() : eof is set.
    • s.good() : none of above three states is set.
    • s.is_open() :
    • s.clear() : reset all condition values in the stream to valid state.
  • operation on flags

    • retrieve : basic_ios::rdstate
    • set : basic_ios::setstate
  • about types:

    • std::ios_base::iostate is type for stream error state flags

References:

  1. http://www.cplusplus.com/reference/ios/ios/fail/
  2. http://www.cplusplus.com/reference/ios/ios/operator_not/
  3. http://stackoverflow.com/questions/6255339/checking-if-a-file-opened-successfully-with-ifstream
  4. http://www.cplusplus.com/forum/beginner/6033/
  5. http://www.cplusplus.com/doc/tutorial/files/
原文地址:https://www.cnblogs.com/nn0p/p/4379396.html