Program for searching a substring from a file.

#include<stdio.h>//HEADER FILES INCLUDED
#include<string.h>                            //FOR strcmp()
//argc=NO OF ARGUEMENTS, argv[]=ARRAY OF THESE ARGS
main(int argc,char *argv[])                       

{
FILE *p1,*p2;                            //POINTERS TO HANDLE FILES
char str[20],c;                            //ARAY TO STORE WORDS
int i,k,l,lcount;
if(argc!=4)                            //CHECKING NO. OF ARGUEMENTS PASSED
{
printf("\n INAPPROPRIATE NO. OF PARAMETERS");
printf("\n CORRECT FORMAT::");
printf("\n ./search <source file> <output file> <search string>");
printf("\n RETRY\n\n");
exit();
}
p1=fopen(argv[1],"r");                        //OPENING FILE-1 IN READ MODE
if(p1==NULL)                            //CHECKING FOR SUCCESS
{
printf("\nERROR IN OPENING THE INPUT FILE\n");
exit();
}
p2=fopen(argv[2],"w");                        //OPENING FILE-2 IN WRITE MODE
if(p2==NULL)                            //CHECKING FOR SUCCESS
{
printf("\nERROR IN OPENING THE OUTPUT FILE\n");
exit();
}
lcount=0;                            //TO COUNT NO. OF LINES
c=getc(p1);                            //READ A CHARACTER FROM FILE
while(c!=EOF)                            //READING TILL END OF FILE
{
i=0;
while(1)
{
if(c=='\n')                    //IF NEW LINE STORE  IN ARRAY AND BREAK
{
str[--i]='';
break;
}
if(c==' ')                    //IF SPACE STORE  IN ARRAY AND BREAK
{
str[i]='';
break;
}
else                        //ELSE STORE THE LETTER IN ARRAY
{
str[i]=c;
i++;
}
c=getc(p1);                    //READ NEXT CHARACTER
}

//l=i;
//printf("\n");
//printf("    %d",strcmp(str,argv[3]));
//printf("    %d",strlen(str));
//printf("    %d   ",lcount+1);
//for(i=0;i<l;i++)
//    printf("%c",str[i]);
if(!strcmp(str,argv[3]))                //IF MATCH FOUND...
fprintf(p2,"%s found at line %d\n",argv[3],lcount+1);        //...WRITE IN THE FILE

if(c=='\n')                        //IF NEW LINE INCREMENT LINE_COUNT
lcount++;
c=getc(p1);                        //READ NEXT CHARACTER
}
//printf("\n");
putc(EOF,p2);                            //PUT EOF IN OUTPUT FILE
fclose(p1);                            //CLOSE FILE-1
fclose(p2);                            //CLOSE FILE-2
printf("\n SEARCH FINISHED");
printf("\n OPEN THE FILE %s TO SEE THE RESULTS\n\n",argv[2]);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s