34

I'm trying to comprehend Example 1.9 from the K&R book, but I don't get how to send EOF. Some sources mentioned Ctr+Z, but that simply terminates the program. I somehow managed to send EOF with a combination of Enter and Ctrl+Z and maybe Ctrl+V, but I can't reproduce it.

#include <stdio.h>
#define MAXLINE 1000

main()
{
    int len;
    int max;
    char line[MAXLINE];
    char save[MAXLINE];

    max = 0;
    while((len = getline_my(line, MAXLINE)) > 0)
    if(len > max) {
        max = len;
        copy(line, save);
    }
    if(max > 0)
        printf("%s", save);
}

getline_my(s, lim)
char s[];
int lim;
{
    int c, i;

    for(i=0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; i++)// As long as the condition is fulfilled
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        i++;
    }
    s[i] = '\0';
    return(i);
}

copy(s1, s2)
char s1[];
char s2[];
{
    int i;

    i = 0;
    while((s2[i] = s1[i]) != '\0')
        i++;

}
1

3 Answers 3

83

You can simulate EOF with CTRL+D (for *nix) or CTRL+Z then Enter (for Windows) from command line.

4
  • 7
    This didn't work for me (Windows 10 + Anaconda Terminal) but the answer provided @mauriceShun did.
    – MrMas
    Commented Dec 10, 2017 at 2:25
  • This does not work on Windows 7 cmd.exe (does not send EOF character that C program is looking for). Commented Sep 23, 2019 at 13:48
  • 17
    On Windows you need to press ENTER after CTRL+Z to actually send it.
    – Carl Walsh
    Commented Nov 23, 2019 at 19:31
  • 1
    ctrl-D needs to stand at the beginning of a line. On mac OS I press return and then ctrl-D. Commented Nov 22, 2022 at 9:53
9

In widows, when you are ready to complete the input, press the Enter key and then press Ctrl+Z and then Enter to complete the input.

int main(){
    char ch[100];    
    scanf("%[^EOF]",ch);    
    printf("\nthe string is:\n%s\n",ch);    
    fflush(stdin);    
    return 0;    
    }
3
  • 5
    scanf("%[^EOF]",ch); and fflush(stdin); are bad.
    – BLUEPIXY
    Commented Dec 8, 2017 at 3:44
  • 5
    This is totally nonsense answer! Commented Jun 22, 2019 at 1:21
  • The text is correct, but the code... is this a joke? What does "%[^EOF]" do? Can you post a resource where this is documented? And what is fflush(stdin) supposed to do?
    – wovano
    Commented Sep 30, 2021 at 5:58
3

In the end, it can't be done easily on Windows given the simple K&R code which was meant for Unix-like systems. You can send '^Z^M' (Ctrl-Z and then Enter) to send Windows equivalent of EOF but the char 'EOF' you are checking for in this C program is not the same.

Short answer: you can't.

Not the answer you're looking for? Browse other questions tagged or ask your own question.