在文件中查找单词 C++

Find words in files c++

我想通过搜索文件夹中的所有文件来查找某个词,下面的示例通过搜索文件夹中的所有文件来查找某个词,下面的示例...

我有文件 1、文件 2 和文件 3 的路径

在文件 1 中包含单词“Apple” 在 file2 中包含单词“Orange” 在文件 3 中包含单词“Banana”

我想让我的程序读出包含单词“Banana”的文件 有人知道吗?我的代码是 C++

对于目录中的每个文件,您可以创建一个“输入文件流”:

std::ifstream myStream(filename);

其中文件名显然必须与文件夹中的文件名相匹配,然后你初始化一个空字符串:

std::string line;

当您读入文件的行时,此字符串将保存它们。现在您创建一个 while 循环,不断从文件中读取行,直到没有更多行为止。如果它找到包含单词“Banana”的行,则输出文件名:

while(getline(myStream, line))
{
    if (line.find("Banana") != std::string::npos)
        std::cout << "Banana was found in: " << filename << std::endl;
}

对目录中的每个文件执行此操作,您需要编写一个遍历目录中文件的循环。

在 C++17 中,引入了文件系统库。这让生活更轻松。

现在,我们有一个迭代器,它使用 directory_iterator 迭代目录中的所有文件。甚至还有一个可用的版本,它将遍历所有子目录。

所以,接下来我们将使用这个迭代器将所有目录条目复制到std::vector。请注意:std::vector 有一个所谓的 range constructor (5)。你给它一个开始和结束迭代器,它用迭代器给定的所有值填充 std::vector 。所以,行:

std::vector fileList(fs::directory_iterator(startPath), {});

会将所有目录条目读入矢量。 {} 将用作默认构造函数,它等于 end iterator.

所以,现在我们有了所有的文件名。我们将循环打开所有常规文件,并将文件完全读入内存。注意:对于大文件,这可能会造成麻烦!

std::vector 类似,std::string 也有一个范围构造函数。作为迭代器,我们将使用 istreambuf 迭代器。这样我们将从打开的文件中读取所有字符。所以,

之后
std::string fileContent(std::istreambuf_iterator<char>(fileStream), {});

文件的完整内容将在 std::string 变量“fileContent”中。

然后,我们用所有查找字符串遍历 std::vector,并使用 std::search.

在“fileContent”字符串中搜索循环字符串

如果我们能找到查找字符串,那么我们会在屏幕上显示文件名和查找字符串。

通过使用现代 C++ 语言元素和库,我们只需几行代码即可完成整个任务:

#include <iostream>
#include <fstream>
#include <filesystem>
#include <vector>
#include <iterator>
#include <algorithm>

// Namespace alias for easier writing
namespace fs = std::filesystem;

// Some demo test path with files
const fs::path startPath{ "c:\temp\" };

// Some test strings that we are looking for
std::vector<std::string> lookUpStrings{ "Apple","Banana","Orange" };

int main() {

    // Get all file names of the files in the specified directory into this vector
    std::vector fileList(fs::directory_iterator(startPath), {});

    // In a loop, open all files an search for lookup strings
    for (const fs::directory_entry& de : fileList) {

        // Open file and check, if it could be opened
        if (fs::is_regular_file(de.path()))
        if (std::ifstream fileStream{ de.path().string() }; fileStream) {

            // Read complete file
            std::string fileContent(std::istreambuf_iterator<char>(fileStream), {});

            // Search for the lookup strings
            for (const std::string& l : lookUpStrings)
                if (std::search(fileContent.begin(), fileContent.end(), l.begin(), l.end()) != fileContent.end())
                    std::cout << "File '" << de.path().string() << "' contains '" << l << "'\n";
        }
        else std::cerr << "\*** Error: Could not open file '" << de.path().string() << "'\n";
    }
    return 0;
}