7

Maybe a dummy question, but I need a clear answer to it. Is there any difference at all in the return of any of those functions

int FileExists(const std::string& filename)
{
  ifstream file(filename.c_str());
  return !!file;
}

int FileExists(const std::string& filename)
{
  ifstream file(filename.c_str());
  return file.is_open();
}

So in other words, my question is: does casting the fstream to bool give exactly the same result as fstream::is_open()?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189
  • As a side note, if you were to make those function return a `bool` (instead of `int`), you probably wouldn't need the `!!` operators. – Alexis Wilke Aug 12 '21 at 20:43

1 Answers1

11

No. is_open checks only whether there is an associated file, while a cast to bool also checks whether the file is ready for I/O operations (e.g. the stream is in a good state) (since C++11).

is_open

Checks if the file stream has an associated file.

std::basic_ios::operator bool

Returns true if the stream has no errors occurred and is ready of I/O operations. Specifically, returns !fail().

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • 1
    So if I understand you correctly, checking whether a file exists should be done using fstream::is_open(), right? – The Quantum Physicist Feb 17 '13 at 11:15
  • @SamerAfach: Both methods are feasible ways to check whether the file exists. However, only the latter is correct if you want to additionally check whether the stream is in a good state. Stick to the one you like most. – Zeta Feb 17 '13 at 11:17
  • Actually I don't care if the file is in a good state for I/O. I just want to know whether the file exists. The file could even be not accessible for user permissions stuff, but yet it exists. Which means fstream::is_open() is the safe option in this case, right? – The Quantum Physicist Feb 17 '13 at 11:20
  • @Samer - No, if the file is not accessible, the `open` is also likely to fail. – Bo Persson Feb 17 '13 at 12:44
  • @Bo Persson Then I don't really see the difference. Can you please give an example where fstream::is_open() will give true and the cast will give false? – The Quantum Physicist Feb 17 '13 at 15:27
  • 3
    @SamerAfach: `ifstream file("test.txt"); int i; file >> i;`. If `test.txt` exists, is empty and could be opened, `file.is_open()` is true, but the extraction of an integer failed and `!!file` is false. Note that a false `is_open` _always_ implies `!!file` false. – Zeta Feb 18 '13 at 00:02