TinCan
TinCan

Reputation: 13

Stop ofstream from creating a file

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"
}

Upvotes: 0

Views: 683

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122298

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.

Upvotes: 1

Related Questions