Tuesday, 19 April 2016

c++ - std::ofstream, check if file exists before writing



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 before writing to it, so that I can prompt a warning to the user.



I am using an std::ofstream and I am not looking for a Boost solution.



Answer



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



#include 
// 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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...