SIMULATION OF UNIX COMMANDS
Programs
// 3. Grep
command
#include <stdio.h>
#include <stdlib.h>
int substr( char *line, char *pat);
int main(int argc, char *argv[])
{
FILE
*fp;
char
line[128];
if (
argc == 2 )
fp = stdin;
else if
( argc == 3 )
{
fp = fopen(argv[2], "r");
if ( fp == NULL )
printf("file %s cannot be opened \n", argv[1]);
}
else
{
printf("Usage: %s <pattern>
<file> \n", argv[0]);
exit(1);
}
while(
fgets(line, sizeof(line), fp) )
if ( substr(line, argv[1]) )
printf("%s",line);
fclose
(fp);
return 0;
}
int substr( char *line, char *pat)
{
int
i,j,k;
for(
i=0; line[i] != '\0'; i++)
for( j=i,k=0; line[j]==pat[k]
&& pat[k] != '\0'; j++,k++);
if ( pat[k] == '\0')
return 1;
return
0;
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu