Thursday 29 September 2011


SIMULATION OF GREP COMMAND

  AIM:
 To implement the grep command in C.

ALGORITHM:

  1. Start the process.
  2. Declare the required variables.
  3. Obtain the filename and the required word to be searched from the user.
  4. Open the file and read the contents till the end of the file.
  5. Search the given word in the file using strstr() function, if it matches, then the word is found.
  6. Do this till the end of file is reached.
  7. Stop the process.

PROGRAM:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
Int calc_butsize(char *filename)
{
Struct stat st;
Stat(filename,&st);
Return((int)st.st_size);
}
Int main(int argc,char *argv[])

{
If(argc<3)
Printf(“usage:\n\t %s <word><files>…..\n”,argv[0]);
Return -1;
}

FILE *fp;
Char *filename;
Int *=2;
For(x;x!=argc;x++)
Filename=argv[x];
If((fp=fopen(filename;”r”))==NULL)
{
Printf(“Failed to open file:%s \n “, argv[2]);
Return -2;
}
Int BUFSIZE=calc_bufsize(filename);
Char buf[BUFSIZE];
Fread(&buf,sizeof(char),BUFSIZE,fp);
Char *ans=strstr(buf,argv[1]);
If(ans!=NULL)
Printf(“%s \n”,filename);
Printf(“the word is found “);
Else
Printf(“ the word is not found in the given file \n”);
Fclose(fp);
}

Return 0;
}


OUTPUT:

[cs28@linux ~]$ ./3b “include” 3b.c
3b.c
The given word is found

RESULT:
 Thus the given C Program is executed and output is verified.

0 comments:

Post a Comment