c++directoryc++17

filesystem error: cannot create directory: No such file or directory


I can't believe no one seems to have posted this error or the solution. I am spinning up on C++ 17.

I am attempting to run the following code.

fs::directory_entry result(CodeSource::ARDUINO_SOURCE);
if (!result.exists()) {
    fs:create_directory(result);
}
return result;

and I get the following result.

terminate called after throwing an instance of 'std::filesystem::__cxx11::filesystem_error'
  what():  filesystem error: cannot create directory: No such file or directory [~/arduino_source]

The variable obviously contains "~/arduino_source" Well of course it doesn't exist. That's why I'm creating it.

The docs say it will perform as if I ran mkdir on it and so I tried it and it worked just fine.

I am running Ubuntu 20.10.


Solution

  • I have written a minimal program, and confirm that it's caused by the path ~/arduino_source, you need an absolute path or relative path, but for the tilde ~ character, it will cause exceptions.

    Since the API directory_entry::directory_entry and std::filesystem::create_directory both can throw, your code needs to handle the exception to make it robust.