如何检查二进制文件中是否存在字符串



我有一个二进制文件(不是文本文件(,大小约为20M,并且我有一条字符串,该文件中可能存在也可能不存在。通常(对于文本文件(,我会使用getline()逐行读取文件,然后使用find检测它,类似于:

bool found = false;
{
std::string stringToLookFor("string to look for");
std::ifstream ifs("myBinaryFile.bin");
std::string line;
while (!found && getline(ifs, line)) {
found = (line.find(stringToLookFor, 0) != std::string::npos);
}
ifs.close();
}

然而,我不确定对于二进制文件这样做是否明智。我主要担心的是,这样一个文件的"行"可能很大。可能是整个20M文件中没有换行符,所以我最终可能会读取一个相当大的字符串进行搜索(这种方法可能也存在其他问题,因此我提出了问题(。

这被认为是一种可行的方法吗?还是我可能会遇到问题?有没有比逐行搜索普通文本更好的方法来搜索二进制文件?

我会咬紧牙关,试试答案。你正在寻找这个:

//...
std::ifstream is(file_name, std::ios::binary);
if (!is)
return -1;
auto res = std::search(std::istream_iterator<char>(is), std::istream_iterator<char>(), pattern.begin(), pattern.end());
//...

它是快速,并且不是一次将文件全部加载到内存中。我不知道基于什么算法。较快的boyer_moore_searcher``boyer_moore_horspool_searcher无法使用,因为它需要随机迭代器。

最简单、最快的方法是,@ZDF在评论中建议如何将整个文件读取到内存中,然后在其内容中搜索字符串:

#include <fstream>
#include <vector>
#include <algorithm>
std::ifstream ifs(filename, std::ios::binary);
ifs.seekg(0, std::ios::end);
auto size = ifs.tellg();
ifs.seekg(0);
std::vector<char> content(size, '');
ifs.read(content.data(), size);
auto res = std::search(content.begin(), content.end(), str.begin(), str.end());

最新更新