0

In the book "The C Programming Language" by Kernighan & Ritchie, the following code appears. (I have replaced getline with getLine to avoid a naming conflict with stdio's getline; did it not exist when the 2nd Edition of the book was written? That's a side question) But this program does not terminate.

I understand that it does not reach EOF, and I don't know how to give it an EOF. I am using the terminal in Ubuntu.

#include <stdio.h>
#define MAXLINE 1000
int getLine(char line[], int maxline);
void copy(char to[], char from[]);
main()
{
    int len;
    int max;
    char line[MAXLINE];
    char longest[MAXLINE];
    max=0;
    while((len = getLine(line,MAXLINE)) > 0)
        if(len > max){
            max = len;
            copy(longest,line);
        }
    if(max > 0)
        printf("%s", longest);
    return 0;
}
int getLine(char s[], int lim)
{
    int c, i;
    for(i=0;i< lim - 1 && (c=getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;
    if(c == '\n'){
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}
void copy(char to[], char from[])
{
    int i;
    i=0;
    while((to[i]=from[i])!='\0')
        ++i;
}

I run the program, and I enter some lines of text and press Enter. I do this a few times; but it doesn't terminate, because no EOF. How do I give it an EOF? Normally I would say that the code is wrong, but this is supposed to be the Bible of C programming, so I assume there is a valid explanation.

1 Answers1

1

If your terminal has defaults Control-D sends an EOF.

This can be changed with the stty command. Control-D is set with stty eof ^D.

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • But there'll hardly ever be a reason (let alone a *good* reason) to change it! (It'd be sorta like reprogramming you car's speedometer to read in Klingon, instead of mph or km/h.) – Steve Summit Aug 10 '19 at 23:25
  • @SteveSummit: I take it you've never used old HP-UX. The defaults were something else. – Joshua Aug 10 '19 at 23:42