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
Can anybody help out?
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;
One solution is strstr().
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
char LookForArray = "\x11\x12\x13";
int Len = sizeof(LookForArray) - 1;
int LookForByte = 0;
std::ifstream is("myfile.bin", std::ios::binary);
while (LookForByte < Len && (c = is.get()) != EOF)
if (c == LookForArray[LookForByte])
else LookForByte = 0;
if (LookForByte == Len)
std::cout <<"item was found" <<std::endl;
std::cout <<"item was not found" <<std::endl;
Another solution is memchr().