std::ofstream, check if file exists before writing

后端 未结 6 1763
予麋鹿
予麋鹿 2020-12-02 13:18

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

6条回答
  •  广开言路
    2020-12-02 13:51

    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.

提交回复
热议问题