我需要为字节序列“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);
注:
- 我不能使用
getline()
。这不是一个文本文件,因此可能没有多少换行符。 - 在我尝试使用多字符缓冲区之前,然后将缓冲区复制到C++字符串,然后使用
string::find()
。这是行不通的,因为整个文件中有很多字符,所以缓冲区中的序列在复制到字符串时会被缩短。
你为什么不一次以4个字符读取而不是1个字符? – twain249
您可以一次读取大块字节,将它们存储在一个字节数组中,并使用'memcmp'或'std :: search'比较它们。如果你愿意,重复直到EOF。 – jweyrich
你是否在一个可以产生grep进程的系统中? – Almo