如何检查含目录符号链接的文件路径?is_symlink返回false的替代方案
问题描述
目录及符号链接的查看结果:
$ ls -l total 4 drwxr-xr-x 2 t domain users 4096 Nov 3 17:55 original lrwxrwxrwx 1 t domain users 8 Nov 3 17:56 symbolic -> original
其中symbolic是指向original目录的符号链接。
original目录的内容:
$ ls -l original/ total 8 -rw-r--r-- 2 t domain users 4096 Nov 3 17:55 mydoc.docx
代码中定义的文件路径:
std::string fileName = "/home/Downloads/symbolic/mydoc.docx"; path filePath(fileName);
核心疑问:如何检查该fileName对应的路径是否关联符号链接?当前is_symlink(filePath)返回false,read_symlink(filePath)返回空路径。希望仅当路径涉及符号链接时调用canonical,现有判断逻辑不生效,求替代方案:
if(is_symlink(filePath)) // 该判断返回false,是否有其他替代方案? { newFilePath = canonical(filePath); }
解决方案
问题根源在于:/home/Downloads/symbolic/mydoc.docx这个路径本身不是符号链接,真正的符号链接是路径中的symbolic目录节点。is_symlink函数检查的是整个路径指向的最终对象,而非路径中是否包含符号链接组件。
可以通过以下两种方式实现需求:
方法一:逐级检查路径组件
遍历路径的每一个父级节点,检查是否存在符号链接:
#include <filesystem> namespace fs = std::filesystem; bool path_contains_symlink(const fs::path& p) { fs::path current = p.root_path(); for (const auto& part : p) { current /= part; if (fs::is_symlink(current)) { return true; } // 若当前节点是文件,停止遍历 if (!fs::is_directory(current)) { break; } } return false; } // 使用示例 if (path_contains_symlink(filePath)) { newFilePath = fs::canonical(filePath); }
方法二:对比原始路径与解析后路径
canonical会解析所有符号链接得到绝对路径,对比原始路径的绝对形式和canonical后的路径,若不一致则说明路径中包含符号链接:
fs::path absolute_path = fs::absolute(filePath); fs::path canonical_path = fs::canonical(filePath); if (absolute_path != canonical_path) { newFilePath = canonical_path; }
注意:canonical要求目标路径必须存在,若路径可能不存在,可改用weakly_canonical,它支持处理不存在的路径。
内容的提问来源于stack exchange,提问作者Anirban Saha
相关产品推荐
相关产品推荐

