简体   繁体   中英

Why does EOF behave differently in fgets and read

#include <stdio.h>

#define MAXLINE 4096

int 
main(int argc, char **argv)
{
    char           *s;
    char            buf[MAXLINE];

    s = fgets(buf, MAXLINE, stdin);    // here, if replaced with read(0, buf, MAXLINE);        

    return 0;
}

Input is :12 ctrl+d

  1. fgets doesn't return until input ctrl+d again(That is: 12 ctrl+dctrl+d ). Why doesn't fgets return when it encounts the first EOF ? It seems 12 ctrl+d doesn't work.

  2. But when s = fgets(buf, MAXLINE, stdin); is replaced with read(0, buf, MAXLINE); read will return(input is also: 12 ctrl+d ).

Hitting CTRL + d on the terminal:

  • simply means flush all the characters in stdin (the input buffer) immediately
  • it does NOT trigger an EOF condition on stdin
    (unless the current line/buffer is co-incidentally empty.)

So hitting CTRL+D while running a program ,

  • a blocked fgetc() will return if you do it twice consecutively.
    1st = flush currently buffered characters,
    2nd = flush empty buffer; ie EOF condition is valid for fgetc() and it returns .
  • a blocked fgetc() will return if you do it once on an empty-line.
    flushes an already empty stdin buffer, ie EOF condition is valid for fgetc() and it returns.
  • a blocked read() returns immediately as soon as the input is flushed.

Checkout the answers to this question for more details.

In common implementations fgets is based on a loop around read . If you call fgets it calls read internally. Typing 1 2 Ctrl+D makes read return the two characters "12" to fgets . That does not yet make a full line, so fgets calls read again. Since we're reading from a terminal device, and not a file for example, read waits for you to type more data. If you type Ctrl+D again, read returns 0 characters, which fgets interprets as an end of file and returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM