Search for a word in file line by line in C programming

Hadeel Swedan picture Hadeel Swedan · Apr 16, 2015 · Viewed 13.9k times · Source

I am trying to write code to search for a word in a file line by line and print the line containing the word. Functions fgets and getline didn't seem to work.

void FindWord(char *word , char *file){
   char *line ;
   line = (char*)malloc(1024) ;
   int fd ;
   fd = open(file , O_RDONLY );
   while (fgets(line , sizeof(line) ,fd )!= NULL)
   {
      if (strstr(line , word )!= NULL)
      {
         printf("%s",line);
      }
   }
}

Answer

R Sahu picture R Sahu · Apr 16, 2015

Problem 1

fgets() needs a FILE* not a file descriptor.

Change

 int fd ;
 fd = open(file , O_RDONLY );

to

 FILE* fp = fopen(file, "r");

and use fp as the argument to fgets.

Problem 2

sizeof(line) doesn't evaluate to 1024, as you are probably expecting. It just evaluates to the size of a pointer, which is most likely 4 or 8.

Change

while (fgets(line , sizeof(line) ,fd )!= NULL)

to

while (fgets(line , 1024, fp )!= NULL)

Update

Also, since you are hard coding 1024 in the call to malloc, you might as well use an array. Then, you can use sizeof(line).

void FindWord(char *word , char *file){
   char line[1024] ;
   FILE* fp = fopen(file, "r") ;
   while (fgets(line , sizeof(line) , fp )!= NULL)
   {
      if (strstr(line , word )!= NULL)
      {
         printf("%s",line);
      }
   }
}