【发布时间】:2010-11-25 21:34:15
【问题描述】:
我有一个 fstream my_file("test.txt"),但我不知道 test.txt 是否存在。如果它存在,我想知道我是否也可以阅读它。该怎么做?
我使用 Linux。
【问题讨论】:
标签: c++ linux file fstream exists
我有一个 fstream my_file("test.txt"),但我不知道 test.txt 是否存在。如果它存在,我想知道我是否也可以阅读它。该怎么做?
我使用 Linux。
【问题讨论】:
标签: c++ linux file fstream exists
【讨论】:
您可以使用Boost.Filesystem。它有一个boost::filesystem::exist 函数。
我不知道如何检查读取访问权限。你也可以查看Boost.Filesystem。然而,除了尝试实际读取文件之外,可能没有其他(便携式)方法。
编辑(2021-08-26): C++17 引入了<filesystem>,你有std::filesystem::exists。不再需要 Boost。
【讨论】:
如果您使用的是 unix,那么 access() 可以告诉您它是否可读。但是,如果 ACL 正在使用中,那么它会变得更加复杂,在这种情况下,最好使用 ifstream 打开文件并尝试读取。如果无法读取,则 ACL 可能会禁止读取。
【讨论】:
什么操作系统/平台?
在 Linux/Unix/MacOSX 上,您可以使用fstat。
在 Windows 上,您可以使用GetFileAttributes。
通常,使用标准 C/C++ IO 函数没有可移植的方法。
【讨论】:
sys/stat.h 中。
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.";
}
}
}
考虑同时检查file type。
【讨论】:
从 C++11 开始,可以使用隐式 operator bool 代替 good():
ifstream my_file("test.txt");
if (my_file) {
// read away
}
【讨论】:
我知道发帖人最终说他们使用的是 Linux,但我有点惊讶没有人提到 Windows 的 PathFileExists() API 调用。
您需要包含Shlwapi.lib 库和Shlwapi.h 头文件。
#pragma comment(lib, "shlwapi.lib")
#include <shlwapi.h>
该函数返回一个BOOL 值,可以这样调用:
if( PathFileExists("C:\\path\\to\\your\\file.ext") )
{
// do something
}
【讨论】: