【问题标题】:Search a file and return path to it in c++ linux在 c++ linux 中搜索一个文件并返回它的路径
【发布时间】:2021-02-11 12:45:15
【问题描述】:

是否存在一个函数,我可以在其中搜索文件并且程序在 linux 上用 c++ 返回它的路径? 我尝试使用 dirent.h,但我不知道如何在递归搜索中获取路径。 谢谢!

【问题讨论】:

    标签: c++ linux file search path


    【解决方案1】:

    是的,在 C++ 上,您可以使用文件系统库。

    #include <filesystem>
    #include <iostream>
    
    namespace fs = std::filesystem; // for brevity
    
    /* fs_search
     * 
     * @param spath - Path to search recursively in ("/home", "/etc", ...)
     * @param term  - Term to search for ("file.txt", "movie.mkv", ...)
     *
     * @returns fs path to the file, if found.
     */
    fs::path fs_search(const std::string & spath, const std::string & term) {
      for (auto & p : fs::recursive_directory_iterator(spath)) {
        if (p.is_regular_file() and p.path().filename() == fs::path(term)) {
          // Return the full path to the file
          return p.path();
        }
      }
    }
    
    int main() {
        std::cout << fs_search("/home", "file.txt") << std::endl;
    }
    

    文件系统库非常广泛和强大,我不会深入探讨,但是文件系统库的文档非常好。 https://en.cppreference.com/w/cpp/filesystem.

    顺便说一句,不要在生产中使用此代码。如果我们没有找到该文件,则没有任何处理。我把那部分留给你。

    @Roy2511 指出: 自 C++17 起仅在 stdc++ 中可用。 在 C++17 之前,它将是 和带有 -lstdc++fs 选项的 std::experimental::filesystem。

    如果 不可用,则使用 boost::filesystem。

    【讨论】:

    • 可能应该提到 &lt;filesystem&gt; 自 C++17 起仅在 stdc++ 中可用。在 C++17 之前,它将是 &lt;experimental/filesystem&gt;std::experimental::filesystem-lstdc++fs 选项。如果&lt;experimental/filesystem&gt; 不可用,则使用boost::filesystem,它们与IIRC 非常相似。
    • 好点@Roy2511,我将您的评论添加到我的答案中。谢谢!
    猜你喜欢
    • 2020-06-22
    • 2015-10-03
    • 2015-02-21
    • 1970-01-01
    • 2015-08-15
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多