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
With std::filesystem::exists of C++17:
#include // C++17
#include
namespace fs = std::filesystem;
int main()
{
fs::path filePath("path/to/my/file.ext");
std::error_code ec; // For using the noexcept overload.
if (!fs::exists(filePath, ec) && !ec)
{
// Save to file, e.g. with std::ofstream file(filePath);
}
else
{
if (ec)
{
std::cerr << ec.message(); // Replace with your error handling.
}
else
{
std::cout << "File " << filePath << " does already exist.";
// Handle overwrite case.
}
}
}
See also std::error_code.
In case you want to check if the path you are writing to is actually a regular file, use std::filesystem::is_regular_file.