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

前端 未结 9 898
我寻月下人不归
我寻月下人不归 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 10:59

    I just saw this test:

    bool getFileExists(const TCHAR *file)
    { 
      return (GetFileAttributes(file) != 0xFFFFFFFF);
    }
    
    0 讨论(0)
  • 2021-01-01 11:06

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

    #include <filesystem> // C++17
    #include <fstream>
    #include <iostream>
    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.
        }
    }
    
    0 讨论(0)
  • 2021-01-01 11:17

    you can also use Boost.

     boost::filesystem::exists( filename );
    

    it works for files and folders.

    And you will have an implementation close to something ready for C++14 in which filesystem should be part of the STL (see here).

    0 讨论(0)
提交回复
热议问题