【发布时间】:2021-02-11 12:45:15
【问题描述】:
是否存在一个函数,我可以在其中搜索文件并且程序在 linux 上用 c++ 返回它的路径? 我尝试使用 dirent.h,但我不知道如何在递归搜索中获取路径。 谢谢!
【问题讨论】:
标签: c++ linux file search path
是否存在一个函数,我可以在其中搜索文件并且程序在 linux 上用 c++ 返回它的路径? 我尝试使用 dirent.h,但我不知道如何在递归搜索中获取路径。 谢谢!
【问题讨论】:
标签: c++ linux file search path
是的,在 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 之前,它将是
如果
【讨论】:
<filesystem> 自 C++17 起仅在 stdc++ 中可用。在 C++17 之前,它将是 <experimental/filesystem> 和 std::experimental::filesystem 和 -lstdc++fs 选项。如果<experimental/filesystem> 不可用,则使用boost::filesystem,它们与IIRC 非常相似。