2

I am reading The C Programming Language (K&R). I am trying to understand how EOF works and I believe that upon encountering Ctrl + D at the beginning of a line, EOF is triggered. However at the end of a line, it requires the user to enter Ctrl + D twice. First to flush the input and the second to trigger EOF.

The following program reads input lines from the console and prints the longest. I don't understand why I have to enter Ctrl + D thrice to trigger EOF.

#include <stdio.h>

#define MAXLINE 1000

int getline(char[]);
void copy(char[], char[]);

int main()
{
    int len, max;

    char line[MAXLINE];
    char longest[MAXLINE];

    max = 0;

    while( (len = getline(line)) > 0)
        if(len > max)
        {
            max = len;
            copy(longest, line);
        }

    if(max > 0)
        printf("%s", longest);
    return 0;

}

int getline(char line[])
{
    int c, i;
    i = 0;

    for(i = 0; i < MAXLINE - 1 && (c = getchar())!=EOF && c!='\n'; ++i )
        line[i] = c;
    if(c == '\n')
    {
        line[i] = c;
        ++i;
    }
    line[i] = '\0';
    return i;
}

void copy(char to[], char from[])
{
    int i = 0;

    while( (to[i] = from[i]) != '\0')
        ++i;
}   
Mwiza
  • 7,780
  • 3
  • 46
  • 42
Hells Guardian
  • 395
  • 1
  • 4
  • 16
  • This actually has nothing to do with your program or the implementation of `getchar`. Instead it's the terminal program which handles `CTRL-D` and closing the input stream. – Some programmer dude Jun 22 '16 at 05:47
  • Related question : http://stackoverflow.com/questions/21260674/why-do-i-need-to-type-ctrl-d-twice-to-mark-end-of-file – msc Jun 22 '16 at 05:53
  • @PaulHankin I need to enter it 3 times at the end of the line. I don't quite understand why. Also, which aspect of the code do you think is incorrect? – Hells Guardian Jun 22 '16 at 05:57
  • 1
    @Rxmsc I understand that but I'd like to know why I need to enter Ctrl + D three times. – Hells Guardian Jun 22 '16 at 06:08

0 Answers0