如何用C语言实现文件内容模糊搜索,读取文件并匹配关键字?
- 内容介绍
- 文章标签
- 相关推荐
本文共计931个文字,预计阅读时间需要4分钟。
不需要额外库,C++标准库就能完成行内字符串搜索。读取文件后,对每一行调用`find`函数,返回`std::string::npos`表示未找到。例如:
注意点:
- 默认大小写敏感,要忽略大小写需先统一转小写(或用
std::search+ 自定义谓词) -
find是精确子串匹配,不支持通配符(如*或?),也不支持正则 - 若文件很大,逐行读取比一次性
std::getline更安全,避免内存溢出
std::ifstream file("log.txt"); std::string line; while (std::getline(file, line)) { if (line.find("error") != std::string::npos) { std::cout << "Match at line: " << line << "\n"; } }
需要通配符或模式匹配就上 std::regex
C++11 起支持 std::regex,能处理 "err.*"、"[Ee]rror" 这类模糊逻辑。
本文共计931个文字,预计阅读时间需要4分钟。
不需要额外库,C++标准库就能完成行内字符串搜索。读取文件后,对每一行调用`find`函数,返回`std::string::npos`表示未找到。例如:
注意点:
- 默认大小写敏感,要忽略大小写需先统一转小写(或用
std::search+ 自定义谓词) -
find是精确子串匹配,不支持通配符(如*或?),也不支持正则 - 若文件很大,逐行读取比一次性
std::getline更安全,避免内存溢出
std::ifstream file("log.txt"); std::string line; while (std::getline(file, line)) { if (line.find("error") != std::string::npos) { std::cout << "Match at line: " << line << "\n"; } }
需要通配符或模式匹配就上 std::regex
C++11 起支持 std::regex,能处理 "err.*"、"[Ee]rror" 这类模糊逻辑。

