[Linux]从控制台一次读取一个字符,无需等待回车键
[Linux]从控制台一次读取一个字符,无需等待回车键
周银辉
读取字符嘛,可以使用getchar(),getch()等等函数,但它们都需要等待回车键以结束输入,而不是按下键盘时立即响应,看上去不那么“实时”。
如果是在windows平台下的话,可以使用conio.h下的_getch()函数,注意是以下划线开头的,msdn链接在这里。
在linux下貌似没有找到类似的函数... 不过可以使用一个比较BT的方式来实现:更改控制台设置。
#include <termios.h>
static struct termios oldt;
//restore terminal settings
void restore_terminal_settings(void)
{
// Apply saved settings
tcsetattr(0, TCSANOW, &oldt);
}
//make terminal read 1 char at a time
void disable_terminal_return(void)
{
struct termios newt;
//save terminal settings
tcgetattr(0, &oldt);
//init new settings
newt = oldt;
//change settings
newt.c_lflag &= ~(ICANON | ECHO);
//apply settings
tcsetattr(0, TCSANOW, &newt);
//make sure settings will be restored when program ends
atexit(restore_terminal_settings);
}
static struct termios oldt;
//restore terminal settings
void restore_terminal_settings(void)
{
// Apply saved settings
tcsetattr(0, TCSANOW, &oldt);
}
//make terminal read 1 char at a time
void disable_terminal_return(void)
{
struct termios newt;
//save terminal settings
tcgetattr(0, &oldt);
//init new settings
newt = oldt;
//change settings
newt.c_lflag &= ~(ICANON | ECHO);
//apply settings
tcsetattr(0, TCSANOW, &newt);
//make sure settings will be restored when program ends
atexit(restore_terminal_settings);
}
下面是一个demo程序,复制粘贴试用吧:
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
static struct termios oldt;
//restore terminal settings
void restore_terminal_settings(void)
{
//Apply saved settings
tcsetattr(0, TCSANOW, &oldt);
}
//make terminal read 1 char at a time
void disable_terminal_return(void)
{
struct termios newt;
//save terminal settings
tcgetattr(0, &oldt);
//init new settings
newt = oldt;
//change settings
newt.c_lflag &= ~(ICANON | ECHO);
//apply settings
tcsetattr(0, TCSANOW, &newt);
//make sure settings will be restored when program ends
atexit(restore_terminal_settings);
}
int main()
{
int ch;
disable_terminal_return();
printf("press your keyboard\n");
/* Key reading loop */
while (1) {
ch = getchar();
if (ch == 'Q') return 0; /* Press 'Q' to quit program */
printf("\tYou pressed %c\n", ch);
}
return 0;
}
#include <stdlib.h>
#include <termios.h>
static struct termios oldt;
//restore terminal settings
void restore_terminal_settings(void)
{
//Apply saved settings
tcsetattr(0, TCSANOW, &oldt);
}
//make terminal read 1 char at a time
void disable_terminal_return(void)
{
struct termios newt;
//save terminal settings
tcgetattr(0, &oldt);
//init new settings
newt = oldt;
//change settings
newt.c_lflag &= ~(ICANON | ECHO);
//apply settings
tcsetattr(0, TCSANOW, &newt);
//make sure settings will be restored when program ends
atexit(restore_terminal_settings);
}
int main()
{
int ch;
disable_terminal_return();
printf("press your keyboard\n");
/* Key reading loop */
while (1) {
ch = getchar();
if (ch == 'Q') return 0; /* Press 'Q' to quit program */
printf("\tYou pressed %c\n", ch);
}
return 0;
}