Hi, i need to search for a string in a file. I am trying to use memcmp() but i have never used this before and have no idea how it works. Looking at its description it compares 2 blocks of memory but im not sure this is what i want to search for a string in a file. I have also found memchr() but this searches for a character not a string. Can anyone help me out by pointing me in the right direction?

Neither of those functions will be useful to you. This is a c++ program, right? Then just use std::string's find() method after reading a line from the file

Here is a complet list of std::string methods.

#include <string>
#include <fstream>
using namespace std;

int main()
{
    string line = "Once upon a time there were three little pigs";
    string search_text = "were";

    string::size_type pos = line.find(search_text);
    if( pos != string::npos)
    {
         // found it
    }
}

i did previously impliment a prog similar but the string im after searching for is a particular set of hex values not ascii characters and i found my program would not pick up the string correctly. to search for string of hex would i not need a mem function?

So, the file you are working with is a binary file, not a text file? Here is one way to code it using memcmp()

unsigned char buf[] = <some binary data>
int bufsize = <size of buf in bytes>
unsigned char search[] = <binary representation of an integer>

// now search buf for a specific int value
for(int i = 0; i < bufsize; ++i)
{
    if( buf[i] == search[0] )
    {
          if( memcmp(&buf[i],search,sizeof(int)) == 0)
          {
                 // found it
           }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.