Search code examples
cfopenfgetsstrcpy

Retrieving / comparing strings in file with user text


I am new to C and am looking to write a program that checks if a word that a user enters is a legit word. I've scoured stackoverflow for suggestions but many are very specific to a particular case. Please before I get flamed, I am aware that this syntax is not correct but looking for some advice on how to fix it. My main problem is how to tell program to check the next line (after the "\0"). And perhaps the while condition is not the best way to tell C check until no more lines exist. In the below code I have sample compare string of "userword" which I use to test but ultimately this will be variable from user input.

#include <stdio.h>
#include <string.h>

int main (void)
{
    FILE *fp;
    fp = fopen("/usr/share/dict/words", "r");
    char line[50];
    while(fgets(line,50,fp) != NULL)
    {
        if(!strcpy(line,"userword"))
        {
            printf("Word exists\n");
            return 0; 
        }
    }
    printf("Word not found, try again.\n");
    return 0;
}

Solution

  • strcpy() copies a string. You should use strcmp() which compares two strings.

    Second, when you read the line from /usr/share/dict/words, there is a newline at the end. You either need to remove the newline (add this after your while and before the if):

    line[strlen(line) - 1] = '\0';
    

    Or compare it to userword\n.