Friday, July 20, 2012

Brute Force String Matching Algorithm In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <errno.h>  
   
 int brute_force();  
   
 char pattern[256]={0};  
   
 int main (){  
   int i=0;  
   char filename[256] = {0};  
   //Get text file  
   printf("Enter path of file to read: ");  
      if (fgets(filename, sizeof(filename), stdin) == NULL){  
        fprintf(stderr, "Invalid input!\n");  
        exit(-1);  
      }  
   
   filename[strlen(filename) - 1] = '\0';  
   FILE *file = fopen(filename, "r");  
     if (!file){  
        fprintf(stderr, "Unable to open %s: %s\n",  
        filename, strerror(errno));  
        exit(-1);  
   }  
   //Get file size  
   fseek(file, 0L, SEEK_END);  
   int sz = ftell(file);  
   fseek(file, 0L, SEEK_SET);  
   //printf("size = %d",sz);  
   //create file size array  
   char buffer[sz];  
   for(i=0;i<sz;i++){  
     buffer[i]=0;  
   }  
   //Get pattern  
   printf("Enter pattern to check : ");  
      if (fgets(pattern, sizeof(pattern), stdin) == NULL){  
        fprintf(stderr, "Invalid input pattern!\n");  
        exit(-1);  
      }  
   pattern[strlen(pattern)-1]='\0';  
      int ch, word = 0;  
      i=0;  
      //put file in to array  
      while ( (ch = fgetc(file)) != EOF ){  
     buffer[i]=ch;  
     i++;  
      }  
   for(i=0;i<sz;i++){  
     printf("%c",buffer[i]);  
   }  
   printf("\n");    
      fclose(file);  
   brute_force(buffer);  
   boyer_moore(buffer);    
     return 0;  
 }  
   
 int brute_force(char *buffer){  
   int k=0,charcmp=0,j=0,i=0;  
   if(strlen(buffer)==0){  
     printf("please choose a file to search\n");  
     return 0;  
   }  
   if(strlen(pattern)==0){  
     printf("please enter a pattern\n");  
     return 0;  
   }  
   if(strlen(buffer)<strlen(pattern)){  
     printf("No matching sub string found");  
     return 0;  
   }  
   printf("Brute Force Algorithm ::\n");  
   while(i<strlen(buffer)){  
     charcmp++;  
     if(pattern[k]==buffer[i]){  
       k++; i++;  
       continue;  
     }  
     else if(pattern[k]=='\0'){  
       printf("\tFound matching substring at %d possition .\n",(i+1-strlen(pattern)));  
       k=0; j=1;  
     }  
     else{  
       i++; k=0; charcmp++;  
     }  
   }  
     if(!j){  
     printf("\tNo matching substring found\n");  
   }  
   printf("\n\tNo of character comparitions = %d \n",charcmp);  
   return 0;  
 }  

1 comments:

  1. Borgata Hotel Casino & Spa in Atlantic City, NJ - Mapyro
    This casino 김포 출장안마 hotel in Atlantic City, NJ is in the historical district of Atlantic City, 출장안마 and is open daily 24 hours. This casino features 5 restaurants, Address: 밀양 출장샵 3131 S. Flamingo Rd, Atlantic City, NJ 08401 남원 출장마사지 Rating: 4.1 · 부천 출장마사지 ‎1,012 reviews

    ReplyDelete