LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C getc without CR (https://www.linuxquestions.org/questions/programming-9/c-getc-without-cr-479522/)

astropirhana 09-01-2006 02: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().

http://www.linux-sxs.org/programming/kbhit.html

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?

Astro

tuxdev 09-01-2006 03:05 PM

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

struct termios cur,raw;
tcgetattr(STDIN_FILENO,&cur);  // get current mode to restore later
raw=cur;
raw.c_lflag&=~(ICANON|ECHO|ISIG);
raw.c_cc[VMIN]=1;
raw.c_cc[VTIME]=0;
tcsetattr(STDIN_FILENO,TCSAFLUSH,&raw);

then return it to cooked mode by doing
Code:

tcsetattr(STDIN_FILENO,TCSAFLUSH,&cur);
You will need to #include <termios.h>

astropirhana 09-01-2006 03:12 PM

Thanks alot
 
Worked great!

Astro

jlliagre 09-01-2006 03: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 03:40 PM

Quote:

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

Actually, there was one difference.
Quote:

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

Quote:

Originally Posted by tuxdev
tcsetattr(STDIN_FILENO,TCSAFLUSH,&raw);

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 04: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 02:01 AM.