Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when fgets encounters EOF in the middle of an input?

Tags:

c

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?

like image 738
Bruce Avatar asked Dec 17 '22 05:12

Bruce


2 Answers

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.

like image 182
William Pursell Avatar answered Apr 07 '23 19:04

William Pursell


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)
like image 34
CB Bailey Avatar answered Apr 07 '23 18:04

CB Bailey