2

I'm writing a program which is going to read a dictionary with the following syntax:

    john
    philips
    dudule
    henry

I have therefore wrote this program:

#define SIZEWORD 10

int main(int argc, char **argv)
{
    /*get dictionary words*/
    FILE * pFile_dictionary;
    char dictionary_name[SIZEWORD];
    int len;
    pFile_dictionary = fopen(argv[1] , "r");

    if (pFile_dictionary == NULL) 
        perror("Error while opening the dictionary");
    else
    {
        while (!feof (pFile_dictionary) )
        {
            if (fgets(dictionary_name , SIZEWORD , pFile_dictionary) == NULL)     
               break;   
       
            printf("Before : dictionary_name is = [%s] \n", dictionary_name);

            /*remove new line*/    
            char *tmp_LF = strrchr(dictionary_name, '\n');
       
            if (tmp_LF != NULL)
                *tmp_LF = '\0';

            printf("After : dictionary_name is = [%s] \n", dictionary_name);        
        } 
    }

    fclose(pFile_dictionary);
    
    return 0;
}

Could someone explain to me why I have this output ? I'm trying to remove the new line added by the fgets function, but it appears to have no effect:

Before : dictionary_name is = [john
] 
After : dictionary_name is = [john
] 
Before : dictionary_name is = [philips
] 
After : dictionary_name is = [philips
] 
Before : dictionary_name is = [dudule
] 
After : dictionary_name is = [dudule
] 
Before : dictionary_name is = [henry
] 
After : dictionary_name is = [henry
] 

Thanks for your help

Ps: Sorry for the bad display, but I'm struggling to understand how to do it easily

Chris
  • 26,361
  • 5
  • 21
  • 42
Syf Illis
  • 145
  • 1
  • 12

1 Answers1

0

A more compact way to remove line endings is with strtok() or strtok_r(). Here I changed your code to use strtok() to eliminate any LF, CR, or both. I also got rid of the EOF check. This will simply loop until fgets() can't read anymore. Of course in a real program you might want to check errno afterward to see if anything went wrong.

while(fgets(dictionary_name, SIZEWORD, pFile_dictionary) != NULL) {
    printf("Before : dictionary_name is = [%s] \n", dictionary_name);
    while(strtok(dictionary_name, "\r\n") != NULL);
    printf("After : dictionary_name is = [%s] \n", dictionary_name);
}

The reason I mention strtok_r, is because strtok is fine for single threaded programs.. and yours is single threaded. But later on, if you work on multi-threaded programs, you have to use strtok_r(), which is thread-safe.

Hope this helps.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
little_birdie
  • 5,600
  • 3
  • 23
  • 28