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

问题描述 投票:1回答:2

我正在尝试创建一个程序,我可以使用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;
    }

"

c++ visual-studio file search directory
2个回答
0
投票

更好的方法是使用新的std::filesystem librarydirectory_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()期望一个函数对象作为最后一个参数应用于每个被访问元素,如果元素匹配我们正在寻找的元素,则返回truestd::find_if()将迭代器返回到此谓词函数返回true的第一个元素,否则返回结束迭代器。在这里,我们使用lambda作为谓词,当我们正在查看的目录条目的路径的文件名组件与所需文件名匹配时,它返回true。然后,我们将std::find_if()返回的迭代器与结束迭代器进行比较,看看我们是否找到了一个条目。如果我们确实找到了一个条目,*found将评估为代表相应文件系统对象的directory_entry

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


0
投票

两种方法都使用findstd::string函数:

   fname.find("abc")

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

您可能想要查看是否有完全匹配,而是使用==。这取决于。

如果找到合适的文件名,则将其推回到矢量中。你的主要功能有

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

它不使用。我怀疑有一些复制/粘贴。

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

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

filter函数还检查".""..",因为它们具有特殊含义 - 当前dir和一个dir。那时,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。

© www.soinside.com 2019 - 2024. All rights reserved.