This question is in regards to the POSIX C function getline
.
The documentation states that getline
returns -1 on error (including EOF), but it doesn't say what becomes of lineptr
or n
in those situations.
I understand that some errors may be handled differently - such as a failed realloc
- but what about EOF? Do lineptr
and n
still retain their original values? Is it implementation specific? Undefined behavior?
If getline return an error (EOF is an error in this function). The data in the buffer should not be used.
EOF
must not be returned if the function reads at least 1 byte, note that the function can return 0 in some case.
Additionally, the manual clearly say:
This buffer should be freed by the user program even if getline() failed.
In either case, on a successful call, *lineptr and *n will be updated to reflect the buffer address and allocated size respectively.
This sentence could be interpreted as the buffer is only updated on a successful call.
In my opinion, the program should log this error and continue with the data that has been already read. Note: Use feof()
to know if the stream has reached the end.
If you look at these POSIX docs http://pubs.opengroup.org/onlinepubs/9699919799/functions/getdelim.html you will see that the function does not return -1 if it reads the last line in the stream and the EOF occurs without a newline (i.e. the last line does not have a newline). So when you reach EOF, the contents of the buffer don't matter because getline will not have written anything into it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With