0

I'm trying open a file and check if it exists yet it creates a new file if the given file does not exist. If it is going to automatically create a file, what's the point of the isOpen() then?

int main() {
std::ofstream defaultFile;
defaultFile.open("AAAAA.txt");
std::cout << defaultFile.is_open();//this will always print out "1"
}
  • `defaultFile.open()` will create a file if it doesn't exist, because `defaultFile` is an output stream. If it succeeds in opening the file (whether it created that file or not) then `defaultFile.is_open()` will return true. Try opening it as an *input* stream - opening will then fail if the file doesn't exist. – Peter Jul 08 '21 at 13:11

1 Answers1

1

what's the point of the isOpen() then?

Creating a file can fail for numerous reasons. One could be that you have no write access in the directory where you try to create the file. In that case

defaultFile.open("AAAAA.txt");

will fail and is_open will return false. If you want to know if the file exists before creating it you can do for example this:

ifstream f(name);
bool exits_and_can_be_opened = f.good();

Taken from here: https://stackoverflow.com/a/12774387/4117728, but note that since C++17 there is the Filesystem library with more straightforward ways to query properties of files.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185