PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 31, 2022

[FIXED] Why does EOF behave differently in fgets and read

 October 31, 2022     c, eof, fgets, linux     No comments   

Issue

#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:12ctrl+d

  1. fgets doesn't return until input ctrl+d again(That is: 12ctrl+dctrl+d). Why doesn't fgets return when it encounts the first EOF? It seems 12ctrl+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: 12ctrl+d).


Solution

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; i.e. 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, i.e. EOF condition is valid for fgetc() and it returns.
  • a blockedread() returns immediately as soon as the input is flushed.

Checkout the answers to this question for more details.



Answered By - TheCodeArtist
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing