Wednesday, August 7, 2019

Brute-force search in C

PROGRAM : 

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void brute_force(char a[],int l)
{
    char n[l];
    int p;
    int q = 0 , i = 0 , j = 0 , k=0 , c=0 , z ;
    printf("\n\n enter the patern ");
    scanf("%s",&n);
    p=strlen(n);
    printf("\n\n enter the number of error you egnore ");
    scanf("%d",&z);
    printf("\n\n text is \n\n");
        printf("%s",a);
    printf("\n\n pattern is \n\n");
        printf("%s",n);
        printf("\n\n length of petern is %d",p);
    printf("\n\n");
    for( i=0 ; i <= (l-p) ; i++ )
    {
        j=0;
        c=0;
        while( (j < p) && (( a[i+j] == n[j] ) || ( c < z )))
        {
            if( a[i+j] != n[j] )
            {
                c=c+1;
            }
                j=j+1;
        }
        if( j == p )
        {
                        printf("\n\n pattern found from position %d",i+1);
                        q=1;
                        k++;
        }
    }

    if(q==0)
    {
        printf("\n string  not found ");
    }

    printf("\n\n pattern found in the text %d times \n\n",k);


}

int main()
{
    FILE *fopen(),*fp;
    char c,n[100],temp,*a;
    int l=0,i;
    printf("\n enter the file name ");
    scanf("%s",&n);
    fp=fopen(n,"r");
    c=getc(fp);
    while(c!=EOF)
    {
        l++;
        c=getc(fp);
    }
    fclose(fp);

    a = (char *)malloc(l*sizeof(char));
    fp=fopen(n,"r");
    c=getc(fp);
    a[0]=c;
    for(i=1;c!=EOF;i++)
    {
        c=getc(fp);
        a[i]=c;
    }
    fclose(fp);

        brute_force(a,l);


}

OUTPUT : 


No comments:

Post a Comment