-1

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.

Spyynk
  • 1
  • 1
  • 2
    What is `buf` defined as? – pmacfarlane May 31 '23 at 10:55
  • 3
    You need an intermediate value of type `int` to read into, to reliably distinguish the value `EOF`. If `buf` is an array of `char`, you've got the same problem described at [Why must the variable used to hold getchar's return value be declared as int?](https://stackoverflow.com/questions/18013167) – Steve Summit May 31 '23 at 10:57
  • 1
    But there may be something else going on here. The expected failure modes (if the variable receiving `fgetc`'s return value is incorrectly declared) are that you fail to detect EOF at all, or that you wrongly detect EOF on receipt of certain input characters such as `ÿ`. If the problem is that you're getting an error rather than an eof condition, I'm not sure what could be causing that. – Steve Summit May 31 '23 at 11:05
  • 1
    Instead of `printf("error")`, use `perror("error")`. This will append a message detailing the actual error encountered. – DevSolar May 31 '23 at 11:21
  • In my real implementation i casted the output of fgets() to char, and buf is an char array (created using calloc). – Spyynk May 31 '23 at 11:39
  • Can't reproduce on my Linux box. I got "eof" printed' – Support Ukraine May 31 '23 at 11:41

2 Answers2

3

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.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

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)

Spyynk
  • 1
  • 1