One of the way would be to do stat() and check on errno.
A sample code would look look this:
#include <sys/stat.h> 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("<path-to-file>", ofstream::out); if (!fp.is_open()) return false; else // do stuff with file
Hope this helps. Thanks!