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.