c++oding="utf-8" ?>
std::filesystem::path::root_path() 直接返回 Windows 驱动器盘符加根目录(如 "C:"),对 UNC 路径返回完整 UNC root,Linux 返回 "/",相对路径返回空;需先规范化路径再调用以确保正确性。

用 std::filesystem::path::root_path() 提取驱动器盘符 + 根目录(Windows)
在 Windows 上,std::filesystem::path::root_path() 返回的就是形如 "C:\" 的驱动器盘符加反斜杠,它不包含后续路径,也不含 trailing slash 以外的多余字符。这是最直接、标准且跨编译器(MSVC / GCC / Clang)一致的方式。
注意:该函数返回的是 std::filesystem::path 类型,不是字符串;需显式转为 string() 或 u8string() 才能打印或拼接。
- 对路径
"C:\Users\Alice\file.txt",p.root_path()返回"C:\" - 对 UNC 路径
"\\server\share\dir",返回"\\server\share\"(即 UNC root) - 对 Linux 路径如
"/home/user",返回"/"(空字符串在 POSIX 下不合法,但root_path()仍返回单个"/") - 若路径不含 root(如相对路径
"data/config.json"),root_path()返回空path—— 此时调用.string().empty()可判断
root_path() 和 root_name()、root_directory() 的区别
这三个成员函数分工明确,混用会导致漏掉盘符或误判根目录:
-
root_name():只取盘符或 UNC 前缀,如"C:"或"\\server\share",不含反斜杠 -
root_directory():只取分隔符部分,Windows 上恒为"\",Linux 上恒为"/" -
root_path()=root_name()+root_directory()(如果两者都存在)—— 这才是你要的完整根表示
错误写法示例:p.root_name().string() + p.root_directory().string() 在 UNC 路径下会多出一个 "\"(因为 root_name() 已含双反斜杠),而 root_path() 自动处理了这种边界情况。
Windows 绝对路径判断 + 提取前必须 normalize
root_path() 对格式敏感:路径未规范化时可能返回空。例如 "C:\temp\..\file.txt" 是绝对路径,但 root_path() 仍有效;而 "C:temp\file.txt"(缺 "\")会被视为相对路径,root_path() 返回空。
- 务必先调用
p = std::filesystem::absolute(p)或p = p.lexically_normal()再取root_path() - 不要依赖
is_absolute()的返回值来跳过 normalize —— 它对"C:file.txt"也返回true,但这不是你想要的“带根目录”的绝对路径 - 推荐组合:
auto abs_p = std::filesystem::absolute(p).lexically_normal(); auto root = abs_p.root_path();
兼容性与编译要求
std::filesystem 在 C++17 中标准化,但早期 GCC(
- MSVC:需确保项目设置中启用了
/std:c++17或更高,并链接libcpmt.lib(静态)或msvcp140.dll(动态) - Clang/GCC:GCC 9+ 默认支持;Clang 需配合 libc++ 或 libstdc++-9+,并加
-lstdc++fs链接选项(GCC 仅 9~11 需显式链接,12+ 自动) - MinGW-w64:部分旧版
libstdc++实现有 bug,建议升级到 GCC 11+ 或改用 UCRT 工具链
真正容易被忽略的是:即使编译通过,root_path() 在非 Windows 平台对普通路径只返回 "/",不会报错也不会模拟盘符 —— 如果你的逻辑隐含“一定有盘符”,就得提前 #ifdef _WIN32 分支处理。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











