How to check if a file exists before creating a new file

前端 未结 9 911
我寻月下人不归
我寻月下人不归 2021-01-01 10:49

I want to input some contents to a file, but I\'d like to check first if a file with the name I wish to create exists. If so, I don\'t want to create any file, even if the f

9条回答
  •  天命终不由人
    2021-01-01 11:06

    C++17, cross-platform: Using std::filesystem::exists and std::filesystem::is_regular_file.

    #include  // C++17
    #include 
    #include 
    namespace fs = std::filesystem;
    
    bool CreateFile(const fs::path& filePath, const std::string& content)
    {
        try
        {
            if (fs::exists(filePath))
            {
                std::cout << filePath << " already exists.";
                return false;
            }
            if (!fs::is_regular_file(filePath))
            {
                std::cout << filePath << " is not a regular file.";
                return false;
            }
        }
        catch (std::exception& e)
        {
            std::cerr << __func__ << ": An error occurred: " << e.what();
            return false;
        }
        std::ofstream file(filePath);
        file << content;
        return true;
    }
    int main()
    {
        if (CreateFile("path/to/the/file.ext", "Content of the file"))
        {
            // Your business logic.
        }
    }
    

提交回复
热议问题