符号链接的boost :: exists不要取消引用

时间:2018-06-03 23:24:23

标签: c++ boost

boost::filesystem中,path类始终尝试取消引用符号链接。很多API都试图让符号链接看起来不可见。我猜他们下面的很多系统调用是stat相关而不是lstat相关。这对我来说是个问题,因为我试图自己获取符号链接。

例如,执行fs::exists("some_symlink")因为虽然存在some_symlink,但它的指示对象不存在。我希望这能让我真实,并且在旧版本的boost中它支持它:https://www.boost.org/doc/libs/1_32_0/libs/filesystem/doc/operations.htm#symbolic_link_exists

然而,现在它没有。这样做有什么好办法吗?

1 个答案:

答案 0 :(得分:2)

您可以使用boost::filesystem::symlink_status获取file_status,然后查看其type()

#include <boost/filesystem.hpp>
#include <iostream>
#include <iomanip>

int main(){
    auto a = boost::filesystem::symlink_status("a_symlink");
    auto b = boost::filesystem::symlink_status("main.cpp");
    auto c = boost::filesystem::symlink_status("not_existing");
    auto d = boost::filesystem::symlink_status("a_broken_symlink");
    std::cout << std::boolalpha
        << (a.type() == boost::filesystem::file_not_found) << " " 
        << (b.type() == boost::filesystem::file_not_found) << " "
        << (c.type() == boost::filesystem::file_not_found) << " "
        << (d.type() == boost::filesystem::file_not_found) << "\n";
}

执行:

$ touch f 
$ ln -s main.cpp a_symlink
$ ln -s f a_broken_symlink
$ rm f 
$ ls -l
total 4
lrwxrwxrwx 1 2001 2000   1 Jun  3 23:33 a_broken_symlink -> f
lrwxrwxrwx 1 2001 2000   8 Jun  3 23:33 a_symlink -> main.cpp
-rw-rw-rw- 1 2001 2000 637 Jun  3 23:33 main.cpp
$ g++ -std=c++14 -Wall -Wextra -pedantic -lboost_filesystem -lboost_system main.cpp && ./a.out
false false true false

Live on Coliru