Checking if file exists?
Is there a method in C++ for checking if a certain file exists in the directory of the program? For example, checking if there is a file named foobar1.txt, and if there is, open a new file named foobar2.txt? Is this possible without using some external library or platform dependant code?
Try to open the file for reading - if that's possible, then it exists. If so, close it and get a new name, repeat until a non-existant name.
It is not entirely perfect, as someone else may have the filename opened in exclusive mode, so you can't open the file - but if the files you are creating aren't likely to be opened in exclusive mode, then that problem can be ignored]
The other potential problem is the race-condition that happens if you have multiple instances, you may end up with two instances trying to creat exactly the same filename/number combination, because both found that files up to 7 exist, so 8 is the right new number.
Both can be solved by trying again if the creation of the new file fails.
You could try opening the file in question for input and see if it fails. Not foolproof, because the file could fail to open for other reasons besides not being present. And of course, race conditions, which can't really be solved.
Originally Posted by Neo1
But if i use std::ofstream foo("bar.txt"), and the file doesn't exist, a new one is created, isn't it? How would i check if a new file is created, or if an existing one is opened?
Open for input, not output. std::ifstream is for input.
Yes ofcourse, i knew that <.<
Originally Posted by Daved
Well, std::ifstream doesn't seem to create a new file when i try to open it, but i'm still not sure how my program would know whether or not ifstream was succesful in opening the file?
Is it possible to do something like this:
So, the bool would be false if ifstream failed in locating the file? In other words, does the constructor for ifstream return a 0 if it fails? And if not, how could i then do it?
file_exists = std::ifstream foo("bar.txt");
//it could open file
Awesome, thanks alot guys :)
Originally Posted by prog-bman
There is also the is_open() function.