#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    Comparing Strings


    I'm making a command line program for Linux that takes one argument(a word) and checks to see if it matches a master list of words in a text file, I'm using strcmp but it's not working.

    Code:
    #include <stdio.h> 
    #include <string.h>  
    int 
    main (int argc, char *argv[]){     
    //Catches invalid command line argument     
    if (argc !=2)     
    {         
        printf("ENTER ONE WORD!");         
        return 1;     
    }     
    char currentLine[8];     
    FILE *wordList;     
    wordList = fopen("/usr/share/dict/words", "r");     
    while(fgets(currentLine, 8, wordList)!=NULL){
        if(strcmp(argv[1], currentLine)==0)             
            printf("foo");    
        }  
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,392
    Rep Power
    1871
    If you have a word like say
    palindrome
    which has 10 letters, then your 8-char buffer will look like this for one call to fgets
    palindr\0
    then
    ome\n\0
    for the second call to fgets.

    Use a larger buffer.

    The other point is that fgets will add a \n for any line that will fit into your buffer. You need to remove the \n before comparing the strings.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0
    How would I go about removing the "\n"??
  6. #4
  7. No Profile Picture
    I haz teh codez!
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2003
    Posts
    2,549
    Rep Power
    2337
    Find it and replace it with a null character?
    I ♥ ManiacDan & requinix

    This is a sig, and not necessarily a comment on the OP:
    Please don't be a help vampire!
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2010
    Posts
    68
    Rep Power
    0
    can anybody explain this code line by line .... i have never used argc and argv

IMN logo majestic logo threadwatch logo seochat tools logo