![]() |
C-Scene
Issues 1..9
Authors
Algorithms Books Patterns Graphics Miscellaneous UNIX Web & XML Windows Feedback FAQs Changes Submissions |
by noss - noss@rm-f.net
last updated 2001/08/22
(version 1.2)
also available as XML
Because of the frequent questions "How do I read one char at a time without waiting for a whole line?" and "How do I get a string from the user without echo of the input?" in IRC channel #c I've decided to write something to point them to.
You often see answers like, "use ncurses", but that is the wrong answer most of the time. The library ncurses is for writing text GUIs, probably not what our aspiring programmer wants to do. Not just yet in her career anyway.
<termios.h>.
int tcgetattr ( int fd, struct termios *termios_p );
int tcsetattr ( int fd, int optional_actions, struct termios *termios_p );
The function tcgetattr() retrieves the current
settings and tcsetattr() changes them, now isn't that
intuitive? Now you just need to find out what to be changed in the
termios struct. The following members are of interest.
tcflag_t c_iflag; /* input modes */ tcflag_t c_oflag; /* output modes */ tcflag_t c_cflag; /* control modes */ tcflag_t c_lflag; /* local modes */ cc_t c_cc[NCCS]; /* control chars */
Even though both echo and line buffering is about input and output
c_lflag is the entry to manipulate. You're not supposed to remember all
this and therefore you have the manpage available. The mask to allow
echo is called ECHO and the mask for line-buffering is part of ICANON.
So what we do is that we clear out these bits from c_lflag.
/* The amazing anykey program written by christian.sunesson@abc.se
* 1998 Oct */
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
struct termios orig, changes;
tcgetattr(STDIN_FILENO, &orig);
changes = orig;
changes.c_lflag &= ~(ICANON|ECHO);
tcsetattr(STDIN_FILENO, TCSADRAIN, &changes);
puts("Hit any key!");
getchar();
puts("Thanks!");
/* restore old settings */
tcsetattr(STDIN_FILENO, TCSADRAIN, &orig);
return 0;
}
1998 Oct. First published
2000 Apr. Rewritten in XML
This article is Copyright © 1998-2000 by Christian Sunesson and Copyright © 1998-2000 by C-Scene. All Rights Reserved.