Question

I want to read strings from a text file (one string/word per line) and then arrange them by size.

This is my code:

void readDic(char* file)
{
    FILE* fr; 
    fr=fopen(file, "rt"); // opening the text file
    char line[MAX_LINE_SIZE];
    char* word;
    while(fgets(line, MAX_LINE_SIZE, fr)!=NULL)
    {
        if(line[0]!='\n')
        {
            word = strtok(line, "\n"); //remove the newline from the string
            // do stuff with word
        }
    } 
    fclose(fr);
}

Although this code code runs, every string I read, except the last one, comes with a size of +1 than the one in the file.

For example, strlen of the string "hello" returns 6 if its anywhere except the last lineof the file. If it is in the last line of the file strlen returns 5.

Am I doing something wrong?

Était-ce utile?

La solution

fgets() does not read C strings. It reads chars until encounters a '\n' ( or EOF condition, or IO error or the buffer is nearly filled). Then it appends a '\0' to the buffer, making the buffer a C string.

After calling fgets(), good to check its return value - which this code did. If NULL, an EOF condition or IO Error exist. Otherwise the buffer contains a C string: 1) an array of char, 2) typically the last is a '\n' and 3) the appended '\0'.

The seemingly extra long result of strlen(line) is from the '\n', which the last line of your text file does not have.

Suggestion to rid the maybe trailing '\n':

size_t len = strlne(line);
if (len > 0 && line[len-1] == '\n') line[--len] = '\0';

Line endings vary between systems: "\r\n" and "\n" are popular, but "\n\r" and "\r" have occurred. By opening the file as a text file "rt", or more portable with "r", the system's typical line ending is converted to "\n" as fgets() requests data from the underlying IO. Given varieties amongst editors, it is possible that the text file that code is reading is using an unexpected line ending and is not translated as mentioned.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top