ifstream

用ifstream实现文件内容的搜索

小樊
82
2024-09-02 19:13:52
栏目: 编程语言

ifstream 是 C++ 中的一个类,用于从文件中读取数据

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

int main() {
    std::ifstream file("example.txt"); // 打开文件 "example.txt"
    std::string search_term = "search_keyword"; // 要搜索的关键字
    std::string line;
    int line_number = 0;
    bool found = false;

    if (file.is_open()) {
        while (std::getline(file, line)) { // 逐行读取文件
            line_number++;
            if (line.find(search_term) != std::string::npos) { // 如果找到关键字
                std::cout << "Found '"<< search_term << "' in line "<< line_number << ": "<< line<< std::endl;
                found = true;
            }
        }
        file.close(); // 关闭文件
    } else {
        std::cout << "Unable to open file"<< std::endl;
    }

    if (!found) {
        std::cout << "'"<< search_term << "' not found in the file"<< std::endl;
    }

    return 0;
}

这个程序首先打开名为 example.txt 的文件。然后,它逐行读取文件内容,并在每一行中搜索指定的关键字(在这个例子中是 search_keyword)。如果找到关键字,程序将输出包含该关键字的行及其行号。如果在文件中没有找到关键字,程序将输出相应的消息。

0
看了该问题的人还看了