Check if directory exists using <filesystem>
Asked Answered
C

2

11

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?

Carbajal answered 31/1, 2022 at 11:12 Comment(1)
Try is_directory(filepath.parent_path()).Disembowel
C
10

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.

Carbajal answered 31/1, 2022 at 11:24 Comment(1)
With C++17 you can also use std::filesystem::exists() for a file or a path (see, en.cppreference.com/w/cpp/filesystem/exists).Yawl
I
3

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.

Irritable answered 31/1, 2022 at 11:20 Comment(1)
Yes, I have need a parent_path() method. ThanksCarbajal

© 2022 - 2024 — McMap. All rights reserved.