Reputation: 578
I have a string that contains the path to some file. The file doesn't need to exist (in my function it can be created), but it's necessary that directory must exist. So I want to check it using the <filesystem>
library.
I tried this code:
std::string filepath = {"C:\\Users\\User\\test.txt"};
bool filepathExists = std::filesystem::exists(filepath);
Also, the path is absolute. For example, for "C:\Users\User\file.txt"
I want to check if "C:\Users\User"
exists.
I have tried to construct a string using iterators: from begin to the last occurrence of '\\'
, but it very rough solution and I get exception if path contains only the name of the file.
Therefore, can somebody provide more elegant way to do it?
Upvotes: 14
Views: 20517
Reputation: 578
The ansewer provided by @ach:
std::filesystem::path filepath = std::string("C:\\Users\\User\\test.txt");
bool filepathExists = std::filesystem::is_directory(filepath.parent_path());
It checks if "C:\Users\User" exists.
Upvotes: 14
Reputation: 180235
This sounds like a job for std::filesystem::weakly_canonical
. It can normalize a path, even if the full path does not (yet) exist.
You can then call .parent_path
on the result to get an absolute path to the parent directory, and check if that path exists.
Upvotes: 3