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

前端 未结 8 1449
时光说笑
时光说笑 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条回答
  • 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 <iostream>
    #include <filesystem> // 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.

    0 讨论(0)
  • 2020-12-13 12:55

    Concerning the use of fstat in windows, I am not sure if it is what you want. From Microsoft the file must be already open. Stat should work for you.

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