【问题标题】:Find circular symlinks with boost filesystem使用 boost 文件系统查找循环符号链接
【发布时间】:2021-02-19 10:18:29
【问题描述】:
我的程序正在递归遍历一个项目目录,其中可能会出现循环符号链接,这会在算法的另一个步骤中引发异常(符号链接的级别太多)。我想找到循环符号链接以避免此类异常。 (不幸的是,通过删除循环符号链接来修复项目不是一种选择。)
有没有办法使用boost::filesystem 来发现循环符号链接?我已经考虑过使用read_symlink() 解析符号链接,并在符号链接解析为另一个符号链接时以递归方式继续它,但这并不是最佳解决方案。
【问题讨论】:
标签:
c++
boost
symlink
boost-filesystem
【解决方案1】:
您应该可以使用boost::filesystem::canonical 或weakly_canonical(以防文件不需要存在)。
请注意,带有许多路径元素的符号链接可能会产生性能开销,因为路径元素是stat-ed,构建一个新的路径实例。
Live On Coliru
#include <boost/filesystem.hpp>
#include <iostream>
int main(int argc, char** argv) {
using namespace boost::filesystem;
for (path link : std::vector(argv+1, argv+argc)) {
boost::system::error_code ec;
auto target = canonical(link, ec);
if (ec) {
std::cerr << link << " -> " << ec.message() << "\n";
} else {
std::cout << link << " -> " << target << "\n";
}
if (ec) {
target = weakly_canonical(link, ec);
if (!ec) {
std::cerr << " -- weakly: -> " << target << "\n";
}
}
}
}
当创建一些不同质量的符号链接时:
ln -sf main.cpp a
ln -sf b b
ln -sf d c
用 a b c d 烧焦它:
"a" -> "/tmp/1613746951-1110913523/main.cpp"
"b" -> Too many levels of symbolic links
"c" -> No such file or directory
-- weakly: -> "c"
"d" -> No such file or directory
-- weakly: -> "d"