【问题标题】:How to check if a file is a regular file or a symlink, using boost::filesystem?如何使用 boost::filesystem 检查文件是常规文件还是符号链接?
【发布时间】:2012-04-18 01:15:49
【问题描述】:

我想检查字符串name 是否引用了我可以打开和读取的文件,因此它可以是常规文件或符号链接。

我第一次使用这个:

std::ifstream in(name.c_str());
if (!in.is_open()) {
  // throw exception!
}

但是当name 引用目录名时它没有抛出异常。

现在我正在使用这个:

if (!fs::exists(name) || fs::is_directory(name)) {
  // throw exception!
}

但如果它是指向目录的符号链接,它将(可能)不会抛出。这也是同样的道理:

if (!fs::is_regular_file(name) && !fs::is_symlink(name)) {
  // throw exception!
}

有没有更好的办法?

【问题讨论】:

    标签: c++ boost boost-filesystem


    【解决方案1】:

    从 Boost.Filesystem v3 开始,检查它是否是常规文件已经可以满足您的需求。下面是一个简单的代码:

    #include <boost/filesystem.hpp>
    
    #include <iostream>
    
    namespace fs = boost::filesystem;
    
    int main(int argc, char* argv[]) {
      if (argc > 1) {
        auto status = fs::status(argv[1]);
    
        if (status.type() == fs::regular_file)
          std::cout << argv[1] << " is a valid path." << std::endl;
        else
          std::cout << argv[1] << " is not a valid path." << std::endl;
    
        if (fs::symlink_status(argv[1]).type() == fs::symlink_file)
          std::cout << "It is also a symlink." << std::endl;
    
      } else {
        std::cerr << "A path must be given." << std::endl;
      }
    
      return 0;
    }
    

    以下是一些输出:

    % ./fstest /bin # it is a symlink path
    /bin is not a valid path.
    It is also a symlink.
    % ./fstest /bin/ # it is a symlink path but dereferenced? (trailing /)
    /bin/ is not a valid path.
    % ./fstest /bin/zsoelim # it is a symlink                                                                                                               
    /bin/zsoelim is a valid path.
    It is also a symlink.
    % ./fstest /bin/soelim # it is not a symlink 
    /bin/soelim is a valid path.
    

    如您所见,boost::filesystem::status(path) 返回有关实际路径的信息,无论它是否是符号链接(跟随到实际位置)。另一方面,boost::filesystem::symlink_status(path) 返回文件本身是否为符号链接的信息。

    更多信息请访问boost docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      相关资源
      最近更新 更多