C Beginner: How to search for particular words in a file (line by line) in C
Asked Answered
S

2

5

I need to search for two particular words in a file line by line and if they exist, print "Found!".

This is file.txt (has four columns)

bill gates 62bill microsoft 
beyonce knowles 300mill entertainment 
my name -$9000 student

The following is the idea I had but it doesn't seem to work

char firstname[];
char lastname[];
char string_0[256];

file = fopen("file.txt","r+");

while((fgets(string_0,256,file)) != NULL) {

  //scans the line then sets 1st and 2nd word to those variables
  fscanf(file,"%s %s",&firstname, &lastname);

  if(strcmp(firstname,"beyonce")==0 && strcmp(lastname,"knowles")==0){
    printf("A match has been found");
  }
}

fclose(file);

Please help. Could it be that the pointer is not moving to the next line in the while loop? And if so, how can i fix?

Stamp answered 20/4, 2012 at 3:17 Comment(2)
what are you doing with string_0, use sscanf(string_9,"%s %s,&firstname,&lastname)Homeric
Now I see that I wasn't doing anything. Tom Dignan helped me out. ThanksStamp
W
5

Instead of calling fscanf on the file after you've already read from it with fgets, you should be calling sscanf on the string_0 variable that you are copying the data to in your fgets call.

Wittgenstein answered 20/4, 2012 at 3:19 Comment(0)
G
4

One way is using the fget function and finding substrings in the text. Try something like this:

int main(int argc, char **argv)
{
    FILE *fp=fopen(argv[1],"r");
    char tmp[256]={0x0};
    while(fp && fget(tmp, sizeof(tmp), fp))
    {
        if (strstr(tmp, "word1"))
            printf("%s", tmp);
        else if (strstr(tmp, "word2"))
            printf("%s", tmp);
    }
    if(fp) fclose(fp);
    return 0;
}
Gorden answered 20/4, 2012 at 3:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.