简体   繁体   中英

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!

Yes, on C++ you can use the filesystem library.

#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;
}

The filesystem library is quite extensive and powerful and I won't go into it too deep, but the docs for the filesystem library are quite good. https://en.cppreference.com/w/cpp/filesystem .

Don't use this code in production, by the way. There's no handling if we don't find the file. I leave that part to you.

@Roy2511 points out that: is only available in stdc++ since C++17. Before C++17, it would be <experimental/filesystem> and std::experimental::filesystem with -lstdc++fs option.

If <experimental/filesystem> is not available, then use boost::filesystem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM