vburns
vburns

Reputation: 11

Reading EOF from getchar() in C on a windows 10 system

I'm working on character K&R C book to try to learn the C language. I'm having a lot of issues because I'm using windows 10 OS instead of Linux. I'm using msys2 to compile and run my code. I for the longest time couldn't figure out the File copying from section 1.5.1 until asking for help from an expert in the field. He pointed out that I needed to use fflush(stdout);

{
    while ((c = getchar()) != EOF) {  // read buffer store in c, then check if it is EOF(ctrl+z on windows)
        fflush(stdout); //flush buffer
        putchar(c);    // print the character retrieved
        printf("%d\n",(c));
    }
    return(0);
}

Adding that made my program work as expected. However, Now I'm running into similar difficulty on the character counter of the next section.

long counter = 0;  // initialize c variable
while (getchar() != EOF) {  //check if character received is EOF(ctrl+z on windows)
    fflush(stdout); //flush buffer
    ++counter;    // incrementcounter
}
fflush(stdout);
printf("%ld\n",(counter));
return(0);

I never see the print on my counter at the end. The attached image shows what happens when I run the file. The "Stopped" print is from when I sent EOF(ctr+Z).

I essentially have two questions:

  1. What exactly happens when I send EOF to my kernel.
  2. Is there a way to send EOF without immediately killing my program? I hope that was easy to follow and thank you all in advance.

Upvotes: 1

Views: 970

Answers (1)

iBug
iBug

Reputation: 37227

What exactly happens when i send EOF to my kernel.

The system (MSYS) tells the program that its standard input has reached EOF (end-of-file), and there'll be no more input availablr.

Is there a way to send EOF without immediately killing my program?

No. Sending an EOF never terminates a program immediately. It lets the program continue without reading input anymore. It's your program that terminates itself when it found nothing to read.

The reason you see Stopped is that you didn't send an EOF at all! Oj Unix shells (including MSYS and Cygwin), Ctrl-Z means Suspend. You can type fg to bring it to foreground again, then press Ctrl-D to send it an EOF.

Note: Ctrl-Z sends EOF only in Windows CMD, and in Windows 10 you have to uncheck a box.

Upvotes: 1

Related Questions