hi i need a litle help.....i must write a program that search for a string in a text file and return the line in the text file were string was found...string its an argv....i wrote this code but it returns the whole text file when i search for something

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

int main(int argc,char *argv[])

{ char caracter[255];

FILE *f;

if(!(f=fopen("File.txt","r")))
{printf("nu este fisierul corect");
exit(1);
}


if(argc>0){



while( fgets(caracter,254,f) !=NULL)

{

if(strcmp(caracter,argv[1]))
printf("%s \n",caracter);
else printf("NOT FOUND");

}

}

return 0;

}

Recommended Answers

All 6 Replies

>if(strcmp(caracter,argv[1]))
strcmp returns a comparison, not a boolean. In other words, 0 is a match and non-zero is a failure to match. Thus, your if statement is reversed. You print the line when it doesn't match argv[1]. This should work better:

if ( strcmp ( caracter, argv[1] ) == 0 )
  puts ( caracter );
else
  puts ( "NOT FOUND" );

i modifyed the program but now its not found for each line of text file...notice that the argv that i enter exists in the txt.....could u write a litle program for me? thx:icon_smile:

>notice that the argv that i enter exists in the txt.....
Yes, but is it the same string you're comparing against? Remember that fgets does not strip the newline character. If you're comparing "test" against "test\n", strcmp will never return 0. You might be better off with strstr instead of strcmp.

>could u write a litle program for me?
Uh, no.

i understand but when run program under linux i wrote ./[name of program] [string to compare] and then i push enter to execute program....that enter is a newline?

now its working.....i used strstr instead of strcmp.....thx very much Narue for helping me:icon_cheesygrin:

>then i push enter to execute program....that enter is a newline?
No, the newline would be coming from the file.

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.