The man page says:
fgets() return s on success, and NULL on error or when end of file occurs while no characters have been read.
I wrote a small C file which calls fgets to test its behavior. I particularly wanted to see what happens when EOF occurs after some characters have been inputted. I used the eof key combination (Ctrl+D) on bash. I had to press Ctrl+D twice for fgets to return. It printed out the characters inputted until I pressed Ctrl+D twice. Pressing Ctrl+D once after some characters had been inputted had no effect at all. If I inputted some characters after this they were stored in the passed array. Why does fgets behave this way?
The behavior you describe has nothing to do with fgets. The shell does not close the input stream until you press ctrl-D the 2nd time.
You should find that if the input ends after at least some characters were read but before a newline is encountered that fgets
returns non-null (a pointer to the supplied buffer) and the supplied buffer won't contain a newline but will be null terminated.
This is just what the documentation for fgets
says.
E.g.
#include <stdio.h>
int main(void)
{
char buffer[200];
char* ret = fgets(buffer, sizeof buffer, stdin);
printf("exit code = %p\n", (void*)ret);
if (ret != 0)
{
printf("read code = %s<--END\n", buffer);
}
return 0;
}
output:
$ printf "no newline here->" | ./a.out
exit code = 0x7fff6ab096c0
read code = no newline here-><--END
or:
$ printf "newline here->\nmore text\n" | ./a.out
exit code = 0x7fff6f59e330
read code = newline here->
<--END
on no input:
$ printf "" | ./a.out
exit code = (nil)
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