I am implementing file saving functionality within a Qt application using C++.
I am looking for a way to check to see if the selected file already exists be
One of the way would be to do stat() and check on errno.
A sample code would look look this:
#include
using namespace std;
// some lines of code...
int fileExist(const string &filePath) {
struct stat statBuff;
if (stat(filePath.c_str(), &statBuff) < 0) {
if (errno == ENOENT) return -ENOENT;
}
else
// do stuff with file
}
This works irrespective of the stream. If you still prefer to check using ofstream just check using is_open().
Example:
ofstream fp.open("", ofstream::out);
if (!fp.is_open())
return false;
else
// do stuff with file
Hope this helps. Thanks!