C++ 文件搜索函数示例:快速查找文本

以下是一个简单的 C++ 函数示例,用于在文件中搜索特定文本字符串。

#include <iostream>
#include <fstream>
#include <string>

void searchFile(std::string fileName, std::string searchString) {
    std::ifstream inputFile(fileName);
    if (!inputFile.is_open()) {
        std::cout << "Error opening file." << std::endl;
        return;
    }
    std::string line;
    int lineNumber = 1;
    while (getline(inputFile, line)) {
        if (line.find(searchString) != std::string::npos) {
            std::cout << fileName << " line " << lineNumber << ": " << line << std::endl;
        }
        lineNumber++;
    }
    inputFile.close();
}

int main() {
    searchFile("example.txt", "hello");
    return 0;
}

该函数接受两个参数:文件名和要搜索的字符串。函数尝试打开指定的文件,并逐行搜索文件中是否包含搜索字符串。如果找到匹配的行,则打印该行和行号。最后,函数关闭文件。

在这个例子中,我们使用了 ifstreamgetline 函数来打开和读取文件。我们还使用了 stringfind 函数来搜索字符串。如果找到搜索字符串,则 find 函数返回字符串中的位置。如果找不到,则返回 std::string::npos 常量。因此,我们可以使用 if 语句来检查是否找到了搜索字符串。

C++ 文件搜索函数示例:快速查找文本

原文地址: https://www.cveoy.top/t/topic/oYMD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录