2

In plain C, how can check if standard input has bytes pending without blocking?

The reason for this is handling escape sequences which are multi-byte.

For example, if I use getchar() and the user presses Ctrl-Up Arrow, then 3 bytes are immediately placed in standard input: 1B 4F 41, however getchar() only reads ONE of those bytes. I need to read all three before continuing on. Different escape sequences are of different length, so the logic is that if the first character is an escape character then I read ALL characters currently in the buffer and then process that as an escape unit. But I can't do that with getchar() because it will block when it reaches the end of the buffer. I need to know how many characters are in the buffer.

Tyler Durden
  • 11,156
  • 9
  • 64
  • 126

1 Answers1

2

There's no such provision in standard C; you need to use OS-specific calls to either do non-blocking reads or, as I think is more appropriate here, to read bytes from the input immediately rather than wait for a newline. For the latter, see

setvbuf not able to make stdin unbuffered

Note:

the logic is that if the first character is an escape character then I read ALL characters currently in the buffer and then process that as an escape unit

That really isn't the way to do it, and will fail if keys are pressed rapidly or are autorepeated, or, say, you're reading from a key log file. Each byte determines how many more bytes of escape sequence there are; you should read conditionally based on what you have already seen.

Community
  • 1
  • 1
Jim Balter
  • 16,163
  • 3
  • 43
  • 66