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){

        char *buff=fgets(buff, 1024,file); //how to get one word at a time???
        if(buff == NULL) break;
        if(strcmp(buff, string) == 0) return true;
    return false;



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) {
        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.

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;

Need Your Help

Using Spring @Value annotation for multiple properties

java spring

I'm using @Value annotation to inject properties and now the properties have increased and the constructor is getting really big .Is there a way to handle this problem

Is there a WatchKit sensor API?

iphone watchkit apple-watch

Is there any API available for Apple Watch Kit sensors such as the accelerometer, heart rate monitor, haptic sensor ?