Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Reading Savitch's Problem Solving in C++, std::ifstream::fail is shown as an example to check if a file has been correctly opened (ifstream or ofstream).

I've previously used, as it is what I was first shown, std::ifstream::is_open to perform the same check.

Which is 'better' practice?

Or in the case that either one is called directly after attempting to open, does it make no practical difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
525 views
Welcome To Ask or Share your Answers For Others

1 Answer

INTRODUCTION

std::ifstream::fail includes checking std::ifstream::is_open, but std::ifstream::is_open only checks if it was possible to create a handle to the file.


EXPLANATION

std::ifstream::fail can return true, even if std::ifstream::is_open returns true; they are not the mutually exclusive.

.fail will check the overall "health" of the stream, which involves things such as checking the stream has currently entered a fail state from trying to read an invalid value, whereas .is_open will only check if the stream is currently attached to a file, .is_open doesn't care if the stream is in a fail state, or not.


WHAT'S THE BETTER PRACTICE?

This certainly depends on what you are trying to accomplish.

Normally it's recommended to rely on the explicit operator bool () to see if a stream is ready to be read/written to. This includes checking the overall health of the stream.

Can we make another read/write operation on some_stream?

if (some_stream) {
  // stream is alive and well
} else {
  // something is wrong
}

If you explicitly would like to see if some fstream is actually attached to a file, use is_open, and if you want to check the overall health; use .fail or rely on the fact that a stream is convertiable to bool.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...