Kim*_*man 82
我可能会选择:
ifstream my_file("test.txt");
if (my_file.good())
{
// read away
}
Run Code Online (Sandbox Code Playgroud)
该good方法检查流是否准备好从中读取.
Ada*_*ura 22
您可以使用Boost.Filesystem.它有一个boost::filesystem::exist功能.
我不知道如何检查读访问权限.您也可以查看Boost.Filesystem.然而,除了尝试实际读取文件之外,可能没有其他(便携式)方式.
Pab*_*ruz 11
什么操作系统/平台?
在Linux/Unix/MacOSX上,您可以使用fstat.
在Windows上,您可以使用GetFileAttributes.
通常,使用标准C/C++ IO函数没有可移植的方法.
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)
还要考虑检查文件类型。
从C++ 11开始,可以使用隐式运算符bool而不是good():
ifstream my_file("test.txt");
if (my_file) {
// read away
}
Run Code Online (Sandbox Code Playgroud)