有没有更好的方法来搜索文件中的字符串?

joh*_*ith 3 c++ search

我需要在(非文本)文件中搜索字节序列"9μ}Æ"(或"\ x39\xb5\x7d\xc6").

在线搜索5个小时后,这是我能做的最好的事情.它有效,但我想知道是否有更好的方法:

char buffer;

int pos=in.tellg();

// search file for string
while(!in.eof()){
    in.read(&buffer, 1);
    pos=in.tellg();
    if(buffer=='9'){
        in.read(&buffer, 1);
        pos=in.tellg();
        if(buffer=='µ'){
            in.read(&buffer, 1);
            pos=in.tellg();
            if(buffer=='}'){
                in.read(&buffer, 1);
                pos=in.tellg();
                if(buffer=='Æ'){
                    cout << "found";
                }
            }
        }
    }

    in.seekg((streampos) pos);
Run Code Online (Sandbox Code Playgroud)

注意:

  • 我不能用getline().它不是文本文件,因此可能没有多少换行符.
  • 在我尝试使用多字符缓冲区然后将缓冲区复制到C++字符串然后使用之前string::find().这不起作用,因为'\0'整个文件中有许多字符,因此当复制到字符串时,缓冲区中的序列会被剪切得很短.

jro*_*rok 5

与bames53发布的内容类似; 我使用矢量作为缓冲区:

std::ifstream ifs("file.bin");

ifs.seekg(0, std::ios::end);
std::streamsize f_size = ifs.tellg();
ifs.seekg(0, std::ios::beg);

std::vector<unsigned char> buffer(f_size);
ifs.read(buffer.data(), f_size);

std::vector<unsigned char> seq = {0x39, 0xb5, 0x7d, 0xc6};

bool found = std::search(buffer.begin(), buffer.end(), seq.begin(), seq.end()) != buffer.end();
Run Code Online (Sandbox Code Playgroud)