Home > Enterprise >  create custom filepath in C
create custom filepath in C

Time:12-30

I need to create a fixed path for the System Drive or C: for most Windows devices. I Need to set C: as the fixed path and build off of it with added directories. So far my code works but wondering if there is a better way. I set it as a string. I know about SHGetKnownFolderPath and FOLDERID but haven't found one for just SYSTEM DRIVE. I am using C 17 and visual studio for this. This is for Windows only devices.

    std::string dir = "C:\\";
    fs::create_directory(dir   "_icons");
    fs::permissions(dir, fs::perms::all);

CodePudding user response:

With std::filesystem, you could start from a C:\ path and query its root_directory().

[Demo]

#include <filesystem>

namespace fs = std::filesystem;

int main() {
    const fs::path c{ "C:\\" };
    auto icons_dir_path{ c.root_directory() / "_icons" };
    if (fs::create_directory(icons_dir_path)) {
        fs::permissions(icons_dir_path, fs::perms::all);
    }
}

Alternatively, you could follow @CaptainObvlious suggestion and:

  1. Get the Windows folder installation via SHGetKnownFolderPath with FOLDERID_Windows as KNOWNFOLDERID.
  2. Extract the drive from the path it returns (for example, via PathGetDriveNumber).
  3. Then, let's say you got the drive in a string windows_drive, you could whether:
  • set std::string dir = windows_drive ":\\"; in the code you posted, or
  • set const fs::path windows_drive_path{ windows_drive ":\\" }; in my example above.

This should be a more robust solution as it would work no matter the drive where Windows is installed.

  • Related