Windows平台C++17系统驱动器固定路径创建的优化方案咨询
动态获取Windows系统驱动器的更优实现方案
硬编码C:\\的方式不可靠——系统驱动器不一定是C盘,下面是两种更稳健的实现方案,基于C++17和Windows原生API:
方案一:通过系统目录提取根路径
利用GetSystemDirectoryW获取系统目录(如C:\Windows),再通过std::filesystem提取根驱动器路径:
#include <windows.h> #include <filesystem> #include <string> namespace fs = std::filesystem; int main() { wchar_t sysDir[MAX_PATH]; if (GetSystemDirectoryW(sysDir, MAX_PATH)) { // 从系统目录路径中提取驱动器根路径(如C:\) fs::path sysDriveRoot = fs::path(sysDir).root_path(); // 创建目标子目录 fs::path iconsDir = sysDriveRoot / "_icons"; fs::create_directory(iconsDir); // 注意:不要给系统根目录设置全权限,仅给子目录分配必要权限 fs::permissions(iconsDir, fs::perms::all); } return 0; }
方案二:读取系统环境变量
直接读取SystemDrive环境变量,这是Windows专门存储系统驱动器的变量:
#include <cstdlib> #include <filesystem> namespace fs = std::filesystem; int main() { const wchar_t* sysDrive = _wgetenv(L"SystemDrive"); if (sysDrive != nullptr) { fs::path sysDriveRoot = fs::path(sysDrive) / L"\\"; fs::path iconsDir = sysDriveRoot / "_icons"; fs::create_directory(iconsDir); fs::permissions(iconsDir, fs::perms::all); } return 0; }
重要提示
- 原代码中给系统根目录(如
C:\)设置fs::perms::all权限极度危险,会导致系统安全漏洞,务必仅对创建的子目录设置权限。 - 优先使用宽字符API(带
W后缀)和std::filesystem的宽字符路径处理,避免中文或特殊字符的编码问题。
内容的提问来源于stack exchange,提问作者Norrin Radd
相关产品推荐
相关产品推荐

