0

Hello!
I am trying to write a program that test whether a word is present in a file or not using command line argument.
Here is my program. It does not work properly. Although the word I entered is present in the file, it has been saying that " the word is not present in the file". What is the problem?

thanks in advance.

#include<stdio.h>
#include<string.h>
int main(int argc,char*argv[])
{
 FILE*ptr;
 char input[100];
 char fstring[100];

 int i=0;
 char* cptr;
 strcpy(input,argv[1]);




 if((ptr=fopen("hello.txt","r"))!=NULL)
 {
     while(!feof(ptr))
     {
       fstring[i++]=getc(ptr);
     }
 }

     fstring[i]='\0';

     ///////////////


     cptr=strstr(fstring,input);
     if(cptr!=NULL)
      printf("%s is present in file",argv[1]);
      else printf("%s is not present in file",argv[1]);

  return 0;
}
2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by nucleon
0

Similar to the other program, this bit is faulty:

if((ptr=fopen("hello.txt","r"))!=NULL)
 {
     while(!feof(ptr))
     {
       fstring[i++]=getc(ptr);
     }
 }

Try something like this:

if((ptr=fopen("hello.txt","r"))==NULL) {
     printf("can't open file\n");
     return -1;
 }
 int c;
 while((c = getc(ptr)) != EOF)
    fstring[i++]=c;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.