如何检查文件是否存在并且在C++中是否可读?

Jer*_*rry 63 c++ linux fstream file exists

我有一个fstream my_file("test.txt"),但我不知道test.txt是否存在.如果它存在,我想知道我是否也可以阅读它.怎么做?

我用的是Linux.

Kim*_*man 82

我可能会选择:

ifstream my_file("test.txt");
if (my_file.good())
{
  // read away
}
Run Code Online (Sandbox Code Playgroud)

good方法检查流是否准备好从中读取.

  • 这样,您不仅可以检查它是否存在且可读,实际上是打开它. (15认同)

Ada*_*ura 22

您可以使用Boost.Filesystem.它有一个boost::filesystem::exist功能.

我不知道如何检查读访问权限.您也可以查看Boost.Filesystem.然而,除了尝试实际读取文件之外,可能没有其他(便携式)方式.


Pab*_*ruz 11

什么操作系统/平台?

在Linux/Unix/MacOSX上,您可以使用fstat.

在Windows上,您可以使用GetFileAttributes.

通常,使用标准C/C++ IO函数没有可移植的方法.


neo*_*eye 10

如果你在unix上,那么access()可以告诉你它是否可读.但是如果正在使用ACL,那么它会变得更复杂,在这种情况下,最好只用ifstream打开文件并尝试读取..如果你无法读取则ACL可能会禁止读取.

  • access()是引入使用时间检查错误的好方法. (2认同)

Roi*_*ton 9

C++17,跨平台:std::filesystem::exists使用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.";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

还要考虑检查文件类型

  • 很好的答案,但问题很简单:我们如何检查*此可执行文件*是否有权读取该文件,而不是*谁有权读取该文件*? (5认同)

Vad*_*zim 5

从C++ 11开始,可以使用隐式运算符bool而不是good():

ifstream my_file("test.txt");
if (my_file) {
  // read away
}
Run Code Online (Sandbox Code Playgroud)