使用Visual Studio C++按名称搜索目录中的文件

Searching for files in a directory by name using Visual Studio C++

本文关键字:文件 搜索 Studio Visual C++ 使用      更新时间:2023-10-16

我正在尝试创建一个程序,在该程序中,我可以使用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_iteratord。然后,我们使用std::find_if()浏览目录的内容,并搜索与我们要查找的文件名匹配的条目。std::find_if()期望一个函数对象作为最后一个参数,该参数应用于每个访问的元素,如果元素与我们要查找的元素匹配,则返回truestd::find_if()将迭代器返回到此谓词函数返回true的第一个元素,否则返回结束迭代器。在这里,我们使用lambda作为谓词,当我们正在查看的目录项的路径的文件名组件与所需的文件名匹配时,该谓词返回true。然后,我们将std::find_if()返回的迭代器与结束迭代器进行比较,看看我们是否找到了条目。如果我们确实找到了一个条目,*found将计算为代表相应文件系统对象的directory_entry

请注意,这将需要Visual Studio 2017的最新版本。不要忘记在项目属性(C++/language(中将语言标准设置为/std:c++17/std:c++latest

这两种方法都使用std::string:的find函数

fname.find("abc")

这将在fname字符串中查找"abc"。如果找到它,它会返回它开始的索引,否则它会重新运行std::string::npos,所以它们都会检查该子字符串。

您可能想看看是否有精确的匹配,请改用==。这取决于情况。

如果找到了一个合适的文件名,它就会被推回到一个向量中。你的主要功能有

std::vector<std::string>::iterator  it;

它不使用。我怀疑这是一些复制/粘贴的结果。

您可以使用基于范围的for循环来查看矢量中的内容:

for(const std::string & name : v)
{
std::cout << name << 'n';
}

filter函数还检查".""..",因为它们有特殊的含义——当前目录和上一个目录。此时,th C API已返回char *,因此它们使用strcmp,而不是std::string方法。


编辑:

n = scandir( dir_path , &namelist, *filter, alphasort );

使用尚未声明的n。尝试

int n = scandir( dir_path , &namelist, *filter, alphasort );

此外,这使用了dir_path,它需要在某个地方声明。

要快速修复,请尝试

const char * dir_path = "C:\";

(或者你想要的任何路径,注意用额外的反斜杠转义反斜杠。

您可能希望将其作为arg传递给main。