Write a program to implement grep command. If word matches with any of the file line, then print that line.
#include<stdio.h> #include<string.h> int main() { FILE *fp; char temp[100],file[32],word[32]; printf("Enter file name = "); scanf("%[^\n]",file); fp = fopen(file,"r"); if(fp == NULL) { printf("file is not present in this directory\n"); return 0; } printf("Enter word to search for = "); scanf("%s",word); while(fgets(temp,100,fp) != NULL) { if(strstr(temp,word)) { printf("%s",temp); } } fclose(fp); return 0; }
Note: File name data is present in the current working directory.
cat data Lot To Learn BlackBerry Iphone Incredible India
Output
./a.out Enter file name = data Enter word to search for = To Lot To Learn
Enter file name = data Enter word to search for = ble Incredible India