-
Searching a binary file
I am trying to write a function which searches a binary file for the occurance of a particular string of characters. I've made some progress but have got a little stuck. Here's what I have come up with so far
Code:
void searchRandomObjectForName(string fname)
{
int index = 0;
string search, name;
cout << "Enter a string to search the file for: " << flush;
cin >> search;
ifstream is(fname.c_str(), ios::binary); // open file to read
// while we can read from the file
while(is.read(reinterpret_cast<char *>(&name), sizeof(int)))
{
// search here, print out string and position in the file
// or print "string not found message."
}
is.close(); // close file when done
cout << endl;
}
Can anybody help out?
-
-
One solution is strstr().
Kuphryn
-
The file is binary, so I guess it'd be safe to assume that strings aren't the best thing to store data in.
Here's one way of doing what you want
Code:
#include <iostream>
#include <fstream>
int main()
{
char LookForArray[] = "\x11\x12\x13";
int Len = sizeof(LookForArray) - 1;
int LookForByte = 0;
int c;
std::ifstream is("myfile.bin", std::ios::binary);
while (LookForByte < Len && (c = is.get()) != EOF)
{
if (c == LookForArray[LookForByte])
LookForByte++;
else LookForByte = 0;
}
if (LookForByte == Len)
{
std::cout <<"item was found" <<std::endl;
}
else
{
std::cout <<"item was not found" <<std::endl;
}
is.close();
}
-
Another solution is memchr().
Kuphryn