我正在尝试创建一个程序,在其中可以使用Visual Studio C ++在PC的目录中搜索某些文件。由于我对此并不十分了解,因此我在另一个答案中找到了该代码(如下),但找不到该代码的任何解释。我很难解决这个问题,将不胜感激。
如果还有另一种方法,我将很高兴知道如何做。谢谢!
“现在您可以获取文件名。只需比较文件名即可。
while ((dirp = readdir(dp)) != NULL) {
std::string fname = dirp->d_name;
if(fname.find("abc") != std::string::npos)
files.push_back(fname);
}
您也可以使用scandir函数来注册过滤器功能。
static int filter(const struct dirent* dir_ent)
{
if (!strcmp(dir_ent->d_name, ".") || !strcmp(dir_ent->d_name, ".."))
return 0;
std::string fname = dir_ent->d_name;
if (fname.find("abc") == std::string::npos) return 0;
return 1;
}
int main()
{
struct dirent **namelist;
std::vector<std::string> v;
std::vector<std::string>::iterator it;
n = scandir( dir_path , &namelist, *filter, alphasort );
for (int i=0; i<n; i++) {
std::string fname = namelist[i]->d_name;
v.push_back(fname);
free(namelist[i]);
}
free(namelist);
return 0;
}
”
更好的方法可能是使用新std::filesystem
库。directory_iterators
允许您浏览目录的内容。由于它们只是迭代器,因此您可以将它们与标准算法结合使用,例如std::find_if
搜索特定条目:
#include <filesystem>
#include <algorithm>
namespace fs = std::filesystem;
void search(const fs::path& directory, const fs::path& file_name)
{
auto d = fs::directory_iterator(directory);
auto found = std::find_if(d, end(d), [&file_name](const auto& dir_entry)
{
return dir_entry.path().filename() == file_name;
});
if (found != end(d))
{
// we have found what we were looking for
}
// ...
}
我们首先directory_iterator
d
为要搜索的目录创建一个。然后std::find_if()
,我们使用浏览目录的内容并搜索与我们要查找的文件名匹配的条目。std::find_if()
期望将函数对象作为最后一个参数应用到每个访问的元素,并true
在元素与我们要查找的内容匹配时返回。std::find_if()
将迭代器返回到此谓词函数true
为其返回的第一个元素,否则返回结束迭代器。在这里,我们使用一个lambda作为谓词,true
当我们正在查找的目录条目的路径的文件名部分与所需的文件名匹配时,该lambda返回。然后,我们比较由std::find_if()
到最终迭代器,以查看是否找到了条目。如果我们确实找到了一个条目,*found
将求值directory_entry
代表一个代表各自文件系统的对象。
请注意,这将需要最新版本的Visual Studio 2017.不要忘记在项目属性(C ++ / Language)中/std:c++17
或/std:c++latest
在项目属性中设置语言标准。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句