29
votes

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++;

}
3
that was for unix .. these are all the commands on cmd ss64.com/nt/syntax-keyboard.htmlOsama Javed

3 Answers

72
votes

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

6
votes

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
votes

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.