Aan
Aan

Reputation: 12890

Find pattern in binary file?

I wrote the function below to find a pattern in a text:

bool match(char* patt,char* text){ 

    int textLoc=0, pattLoc=0, textStart=0;  

    while(textLoc < (int) strlen(text) && pattLoc < (int)strlen(patt)){ 

        if( *(patt+pattLoc) == *(text+textLoc) ){     
            textLoc= textLoc+1;          
            pattLoc= pattLoc+1;      
        }   
        else{          
            textStart=textStart+1;  
        textLoc=textStart;           
        pattLoc=0;   
        }     
    }   


    if(pattLoc >=    (int) strlen(patt)) 
        return true;  
    else return false; 

} 

As it appears, the function takes two parameters of the type char*. I would like to use this function to find a pattern in a binary file, what you suggest to carry out this issue?

Upvotes: 1

Views: 2080

Answers (3)

Chibueze Opata
Chibueze Opata

Reputation: 10054

You sound more like you are looking for the best way to find patterns in files. If so, there is a very good document for single and multiple pattern checking:

Given a pattern P = a1a2...an, Fnd all occurrences of P in a text T = b1b2...bm.

Extension to multipattern cases: Given a set of patterns, P1, P2, ..., Pl ,

Fnd all occurrences of P in a text T = b1b2...bm.

You can check this document for simple explanation and this one for more detailed and different implementations/codes.

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41625

It seems to me that you tried to implement the popular strstr function on your own. But that will not help you, since you asked for finding a binary pattern. The function you should use in that case is called memmem.

Upvotes: 1

Nuno_147
Nuno_147

Reputation: 2913

There is no right or wrong here. The only difference I would consider here is to use buffer/size approach instead of strings.

You should also consider how you would like to read the file. Are you going to read the entire file to memory or are you going to read it in sections ?

If you are going to read it in sections, always save the last part of each section ( the size of your search pattern ) and append it to the beginning of your next section. This way the cuts-off for each section will be evaluated as well.

Upvotes: 1

Related Questions