我怎样从终端读取单个字符?我的程序总是要等着用户按回车。
终端通常在标准(canonical)模式,在此模式输入总是经编辑后以行读入。你可以 设置终端为非标准(non-canonical)模式,而在此模式下你可以设置在输入传递给 你的程序前读入多少字符。你也可以设定非标准模式的计时器为0,这个计时器 根据设定的时间间隔清空你的缓冲区。这样做使你可以使用‘getc()’函数立即 获得用户的按键输入。我们使用的‘tcgetattr()’函数和‘tcsetattr()’函数都 是在POSIX中定义用来操纵‘termios’结构的。
#include <stdlib.h>
#include <stdio.h>
#include <termios.h>
#include <string.h>
static struct termios stored_settings;
void set_keypress(void)
{
struct termios new_settings;
tcgetattr(0,&stored_settings);
new_settings = stored_settings;
/* Disable canonical mode, and set buffer size to 1 byte */
new_settings.c_lflag &= (~ICANON);
new_settings.c_cc[VTIME] = 0;
new_settings.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&new_settings);
return;
}
void reset_keypress(void)
{
tcsetattr(0,TCSANOW,&stored_settings);
return;
}