Home > Software design >  Check if a path is valid, even if it doesn't exist
Check if a path is valid, even if it doesn't exist

Time:04-12

Let's say I have a program that takes paths to the input and output directories from a command line. If the output directory doesn't exist, our program needs to create it. I would like to check (preferably using std::filesystem) if that path is valid, before sending it to std::filesystem::create_directory().

What is the best way to do it?

CodePudding user response:

You gain nothing by doing (pseudo-code alert):

if (doesnt_exist(dir)) {
    create_directory(dir);
}

Better to just do:

create_directory(dir);

And handle errors properly if necessary. You may not even need to handle errors here if you handle subsequent errors.

The "if exists" check introduces unnecessary complexity, and introduces a race condition. And even if the directory doesn't exist, you may still not have permission to create it. So in any case your error handling will be the same, rendering the "if exists" check completely pointless.

I guess it's another way of "don't ask permission, ask forgiveness" except with computers you don't need to ask forgiveness.

CodePudding user response:

Only way to know for sure it to try to use the path. Even if the path is in a correct format or exists in the filesystem, you might not be able to use it.

Some examples of technically valid paths that you cannot use:

  • It is in the personal directory of another user, but you have no permission to write or even read it
  • It is a file that exists, so you cannot create the same path as a directory
  • It is on a removable disk that cannot be written on
  • It is on a network computer that is not connected at the moment
  • It is a web path, but the domain name is not in use

CodePudding user response:

The exists() function checks for that.

std::string my_path = "my_folder_path";
if(!std::filesystem::exists(my_path)) {
  std::filesystem::create_directory(my_path);
}
  • Related