Using C, How will you search for a word in file ?

If i enter an ID Number it should look in the .txt file the employee who owns that ID Number then it will display it on the screen..

Showing Answers 1 - 15 of 15 Answers

the_code

  • Aug 24th, 2011
 

This is a short program to search a string in a file. This prints the line in which the string is found:

Code
  1. #include<stdio.h>

  2. #include<string.h>

  3.  

  4. int main()

  5. {

  6.         FILE *fp;

  7.         char filename[]="name.txt",line[200],search_string[]="12";

  8.         fp=fopen(filename,"r");

  9.         if(!fp)

  10.         {

  11.                 perror("could not find the file

  12. ");

  13.                 exit(0);

  14.         }

  15.         while ( fgets ( line, 200, fp ) != NULL ) /* read a line */

  16.         {

  17.                 if(strstr(line,search_string))

  18.                 fputs ( line, stdout ); /* write the line */

  19.         }

  20.         fclose ( fp );

  21.         return 0;

  22. }

Jonatan

  • May 11th, 2016
 

I dont think it will work right... if you are search for the word "be", and you have on the text the word "best" the function strstr is gonna found...

  Was this answer useful?  Yes

Tried for basic level format, here i cant get complete string with spaces but if you use "_" instead of " " you might get it.

Code
  1. void search_books()

  2. {

  3.     int flag=0;

  4.     lib l;

  5.     FILE *fp;

  6.     char book_name[50];

  7.     fp=fopen("LBS.txt","r");

  8.     system("cls");

  9.     printf("Book Name?

  10. ");

  11.     scanf("%s",book_name);

  12.     while(fread(&l,sizeof(lib),1,fp)!=0)

  13.     {

  14.         if(strcmp(book_name,l.Book_Name)==0)

  15.         {

  16.             printf("

  17. Book Found!!!

  18. ");

  19.             printf("%s Written by %s

  20.  

  21. ",l.Book_Name,l.Author_Name);

  22.             flag=1;

  23.         }

  24.     }

  25.     if(flag==0)

  26.      printf("

  27. Book is currently not available Better Add one to the Book Shelf!

  28.  

  29. ");

  30.     system("pause");

  31.     fclose(fp);

  32. }

  Was this answer useful?  Yes

How is the file structured? Is it a text or binary file? Is it a flat file or a tree structure? Are the records fixed or variable length? Is there a delimiter between the ID and name? Are records in the file ordered by name or ID number?

  Was this answer useful?  Yes

Tanmay Hatkar

  • Oct 8th, 2019
 

Can you please show me how to read a file until whitespace without using lib var type

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions