Do you want to publish source codes in your blog or web site as follows.
Visit Source Code Formatter
Visit Source Code Formatter
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int found_f=0,found_r=0,pat_val=0;
int main (){
system("clear");
while(1){
int i,j=0;
char pattern[256]={0};
char filename[256] = {0};
//Get file
printf("Enter path of file to read(q to exit): ");
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(filename[0]=='q'){
system("clear");
printf("Program Exited!!!\n");
exit(0);
}
if (!file){
fprintf(stderr, "Unable to open %s: %s\n",
filename, strerror(errno));
continue;
}
//Get file size
fseek(file, 0L, SEEK_END);
int sz = ftell(file);
fseek(file, 0L, SEEK_SET);
//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';
for(i=0;i<strlen(pattern);i++){
pat_val=pat_val+pattern[i]; //ascii value of pattern
}
int ch= 0;
printf("\n");
//Get char by char from file
while ( (ch = fgetc(file)) != EOF ){
buffer[j]=ch;
j++;
find(&buffer,&pattern);
}
if(!found_f){
printf("No matching sub string found in forword comparition\n");
}
if(!found_r){
printf("No matching sub string found in reverse comparition\n");
}
//for(i=0;i<sz;i++){
// printf("%c",buffer[i]);
//}
found_f=0;
found_r=0;
pat_val=0;
printf("\n");
fclose(file);
}
return 0;
}
int find(char *buffer,char *pattern){
int i=0,k=0,l=0;
if(strlen(buffer)<strlen(pattern)){
return 0;
}
else{
for(i=strlen(buffer)-strlen(pattern);i<strlen(buffer);i++){
int key=0;
for(k=i;k<(strlen(pattern)+i);k++){
key=key+buffer[k]; //ascii value of key
}
if(key==pat_val){
int m=0,n=0;
//Forword comparition
for(l=0;l<strlen(pattern);l++){
if(pattern[l]==buffer[i+l]){
n++;
}
else{
break;
}
}
if(n==strlen(pattern)){
printf("Matching sub string found in forword signal in %d possition.\n",i+1);
found_f=1;
}
n=0;
//Reverse comparition
for(l=strlen(pattern)-1;l>=0;l--,m++){
if(pattern[l]==buffer[i+m]){
n++;
}
else{
break;
}
}
if(n==strlen(pattern)){
printf("Matching sub string found in reverse signal in %d possition.\n",i+m);
found_r=1;
}
}
}
}
}
0 comments:
Post a Comment