在c++中创建自定义文件路径



我需要为大多数Windows设备的系统驱动器或C:创建一个固定的路径。我需要将C:设置为固定路径,并在此基础上添加目录。到目前为止,我的代码工作,但想知道是否有更好的方法。我把它设为字符串。我知道SHGetKnownFolderPath和FOLDERID,但还没有找到一个只是系统驱动器。我正在使用c++ 17和visual studio为此。

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

对于std::filesystem,您可以从C:路径开始查询其root_directory()

(演示)

#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);
}
}

或者,您可以遵循@ captainobvous建议和:

  1. 通过SHGetKnownFolderPath获取Windows文件夹安装,FOLDERID_Windows作为KNOWNFOLDERID
  2. 从它返回的路径中提取驱动器(例如,通过PathGetDriveNumber)。
  3. 然后,假设您获得了windows_drive字符串的驱动器,您可以是否:
  • 在你发布的代码中设置std::string dir = windows_drive + ":\";,或者
  • 在上面的例子中设置const fs::path windows_drive_path{ windows_drive + ":\" };

这应该是一个更健壮的解决方案,因为无论Windows安装在哪个驱动器上,它都可以工作。

最新更新