Samantha
Samantha

Reputation: 1

Difference between if(file) and if(file.good())?

So I looked here on info on how to check for whether a file exists or not:

The best way to check if a file exists using standard C/C++

They say if(ifile) before checking and then adding an else statement. I usually put if(myfile.good()) to check for the same thing.

Is there a difference in how it operates?

Upvotes: 0

Views: 3061

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595392

For purposes of checking if a file stream is opened successfully, both good() and the bool operator are identical.

There is only 1 subtle difference between good() and the bool operator, and that is good() returns true only if none of the stream's state flags are set, whereas the bool operator returns true if either good() is true or if only the eofbit flag is set. So this difference doesn't come into play until you start reading data from the stream.

Note that the stream also has an is_open() method, as well.

That being said - that article's code only checks if a file can be opened, not if the file exists. A file can exist but you might not have rights to open it. A better way to check for existence is to use std::filesystem::exists(), which that article predates. Just note that checking for a file's existence prior to opening/creating the file will introduce a race condition. Another process could create/delete the file after you check its existence and before you open/create the file yourself.

Upvotes: 1

Related Questions