You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:55:08