std::ofstream, check if file exists before writing

This is one of my favorite tuck-away functions I keep on hand for multiple uses.

#include <sys/stat.h>
// Function: fileExists
/**
 *  Check if a file exists
 *
 * @param[in] filename - the name of the file to check
 *
 * @return    true if the file exists, else false
*/
bool fileExists(const std::string& filename)
{
    struct stat buf;
    if (stat(filename.c_str(), &buf) != -1)
    {
        return true;
    }
    return false;
}

I find this much more tasteful than trying to open a file if you have no immediate intentions of using it for I/O.

Leave a Comment