Gavin Z.
Gavin Z.

Reputation: 431

Find a word in a file?

How do I search for a string in a file? I want to scan one word at a time and compare this to the *string, how can I do that?

bool searchMatch(char *string, FILE *file){

    while(true){
        char *buff=fgets(buff, 1024,file); //how to get one word at a time???
        printf("BUFF=%s\n",buff);
        if(buff == NULL) break;
        if(strcmp(buff, string) == 0) return true;
    }
    return false;

}

Upvotes: 0

Views: 101

Answers (2)

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21213

C's stdio routines have no idea of what a 'word' is. The closest you can have is to use fscanf() to read sequences of characters separated by spaces:

int searchMatch(char *string, FILE *file) {
    char buff[1024];
    while (fscanf(file, "%1023s", buff) == 1) {
        printf("BUFF=%s\n",buff);
        if (strcmp(buff, string) == 0) return 1;
    }
    return 0;
}

This may or may not fulfill your definition of a word. Note that things like "Example test123" are interpreted as two words: "Example" and "test123".

Also, your original code would never work, because you didn't allocate space for buff. fgets() does not allocate memory for you, buff must be a pointer to a valid allocated memory block.

Note that the loop condition was changed so that it implicitly stops when no more input is available - it is generally a good practice to let loops stop when the condition is false, rather than scattering a bunch of break instructions in its body.

Upvotes: 1

Diego R. Alcantara
Diego R. Alcantara

Reputation: 114

Try using the strstr() function, it won't compare word by word, but it can help you telling you if string is in buff Example:

      If(strstr(buff, string)) return 0;

Upvotes: 1

Related Questions