How to check if a file exists and is readable in C++?

前端 未结 8 1491
时光说笑
时光说笑 2020-12-13 12:19

I\'ve got a fstream my_file(\"test.txt\"), but I don\'t know if test.txt exists. In case it exists, I would like to know if I can read it, too. How to do that?

I

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 12:48

    C++17, cross-platform: Check file existence with std::filesystem::exists and readability with std::filesystem::status & std::filesystem::perms:

    #include 
    #include  // C++17
    namespace fs = std::filesystem;
    
    /*! \return True if owner, group and others have read permission,
                i.e. at least 0444.
    */
    bool IsReadable(const fs::path& p)
    {
        std::error_code ec; // For noexcept overload usage.
        auto perms = fs::status(p, ec).permissions();
        if ((perms & fs::perms::owner_read) != fs::perms::none &&
            (perms & fs::perms::group_read) != fs::perms::none &&
            (perms & fs::perms::others_read) != fs::perms::none
            )
        {
            return true;
        }
        return false;
    }
    
    int main()
    {
        fs::path filePath("path/to/test.txt");
        std::error_code ec; // For noexcept overload usage.
        if (fs::exists(filePath, ec) && !ec)
        {
            if (IsReadable(filePath))
            {
                std::cout << filePath << " exists and is readable.";
            }
        }
    }
    

    Consider also checking for the file type.

提交回复
热议问题