Spy
Spy

Reputation: 1

How to properly check for ctrl-d in user input when using fgetc(stdin) in C?

I'm trying to read user input into a buffer by using fgetc(stdin) in c. But apparently i am using it in a wrong way, for determining if the user wants to close the program. What am i doing wrong, and how can i check for ctrl-d correctly, to terminate my program.

My code looks like this:

int read_chars = 0;
while((buf[read_chars] = fgetc(stdin)) != EOF) {
    //do stuff, (change size of buf, break on \n...)
    read_chars++;
}
if(feof(stdin)) {
    printf("eof");
    //exit(EXIT_SUCCESS)
}
if(ferror(stdin)) {
    printf("error");
    //exit(EXIT_FAILURE), ...
}

This works fine, until i press ctrl-d. When i do so, "error" is immediately printed.

Upvotes: -1

Views: 111

Answers (2)

Spy
Spy

Reputation: 1

After i updated my system it now works as it should (feof(stdin) is returning nonzero if ctrl-D is pressed -> the program terminates successfully). I still don't know what caused the error, but the code works. (Maybe it even was an other read of stdin, which put an error indicator, i cant tell, as i changed nothing and it works now)

Upvotes: 0

John Bode
John Bode

Reputation: 123578

Try something like this:

int c;
...
while ((c = fgetc( stdin )) != EOF )
{
  buf[read_chars++] = c;
}

fgetc returns an int, not char. There is no EOF character as such; it's just a value indicating that there is no more input on the stream.

Upvotes: 3

Related Questions