Search code examples
c++filedirectoryutilitiesstd-filesystem

Check if directory exists using <filesystem>


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?


Solution

  • 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.