c++ - 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++ 上,您可以使用文件系统库。
#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。
推荐阅读
- javascript - 如何根据javascript中的数组对象打印出特定的文本?
- google-closure-templates - 闭包模板 - 为复杂的“记录”定义创建一个可重用的别名
- typescript - Next.js typescript 使用 babel-plugin-module-resolver 导入别名
- reactjs - 我可以在没有绑定的情况下使用调度吗?
- shell - 带有许多反斜杠的回声行为
- python - 将日期时间格式从破折号更改为斜杠
- javascript - Typescript Reduce 返回错误的类型
- python - 在本地主机上运行烧瓶服务器错误连接被拒绝
- python - 为什么我的使用 smtplib 发送电子邮件的机器人不起作用?
- subtype - 是 (A -> B) /\ (C -> D) <: (A /\ C) -> (B /\ D)?