使用 <filesystem> 检查目录是否存在

Dar*_*nix 9 c++ directory utilities file std-filesystem

我有一个包含某个文件路径的字符串。该文件不需要存在(在我的函数中可以创建它),但目录必须存在。所以我想使用<filesystem>库来检查它。我尝试了这段代码:

std::string filepath = {"C:\\Users\\User\\test.txt"};
bool filepathExists = std::filesystem::exists(filepath);
Run Code Online (Sandbox Code Playgroud)

另外,路径是绝对的。例如,"C:\Users\User\file.txt"我想检查是否"C:\Users\User"存在。我尝试使用迭代器构造一个字符串:从开始到最后一次出现'\\',但它的解决方案非常粗糙,如果路径仅包含文件名,我会得到异常。

因此,有人可以提供更优雅的方法吗?

Dar*_*nix 6

@ach提供的答案:

std::filesystem::path filepath = std::string("C:\\Users\\User\\test.txt");
bool filepathExists = std::filesystem::is_directory(filepath.parent_path());
Run Code Online (Sandbox Code Playgroud)

它检查“C:\Users\User”是否存在。

  • 使用 C++17,您还可以对文件或路径使用 std::filesystem::exists() (请参阅 https://en.cppreference.com/w/cpp/filesystem/exists)。 (2认同)