-   Programming (
-   -   C getc without CR (

astropirhana 09-01-2006 03:41 PM

C getc without CR
I am trying to get input from the keyboard character by character.

I am writing my code in C.

The problem with getc and fgetc are that they force the user to enter a carriage return and then all buffered characters appear to be returned one at a time and processed. I want to process them immediatly not waiting for the carriage return key to be struck.

I found some code that mimmics the dos command kbhit().

This code almost works 100%...actually 95%.

There are a few bugs. I am using it, and it is working alright. I have to work around a few shortcomings.

What is the recommended way to do this with Linux?


tuxdev 09-01-2006 04:05 PM

getc and fgetc aren't why buffering happens. Buffering is a file stream attribute.
You can switch to raw mode by doing

struct termios cur,raw;
tcgetattr(STDIN_FILENO,&cur);  // get current mode to restore later

then return it to cooked mode by doing

You will need to #include <termios.h>

astropirhana 09-01-2006 04:12 PM

Thanks alot
Worked great!


jlliagre 09-01-2006 04:21 PM

tuxdev is actually suggesting the same solution you already use with kbhit.

What are the 5% cases where you observe it doesn't work ?

KenJackson 09-01-2006 04:40 PM


Originally Posted by jlliagre
tuxdev is actually suggesting the same solution you already use with kbhit.

Actually, there was one difference.

Originally Posted by kbhit
tcsetattr(0, TCSANOW, &new_settings);


Originally Posted by tuxdev

TCSANOW changes immediately, TCSAFLUSH discards input already received. It's not clear if this will make any difference for stdin though.

tuxdev 09-01-2006 05:03 PM

Oh yeah, didn't read that. I guess the difference might be that in this case, the simplicity of using the main library directly causes less errors than complicated mystery code in a library.

Edit: didn't refresh page to see newer comment. I'm not sure if it makes a difference, I pulled that more or less from the code example in Advanced Programming in the Unix Enviroment, originally used in a homework assignment.

All times are GMT -5. The time now is 01:25 PM.