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;
}

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;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.