首页 > 解决方案 > Search a file and return path to it in c++ linux

问题描述

Exist there a function where i can search a file and the program return the path to it in c++ on linux? I tried with dirent.h but i don't know how to get the path in that recursive search. Thanks!

标签: c++linuxfilesearchpath

解决方案


是的,在 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 之前,它将是 <experimental/filesystem> 和带有 -lstdc++fs 选项的 std::experimental::filesystem 。

如果 <experimental/filesystem> 不可用,则使用 boost::filesystem。


推荐阅读