现在的位置: 首页 > 综合 > 正文

linux 终端 读取每个字符

2012年03月05日 ⁄ 综合 ⁄ 共 1734字 ⁄ 字号 评论关闭

以下内容来自 beginning linux programming一书第5章 终端

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
char *menu[] = {
"a - add new record",
"d - delete record",
"q - quit",
NULL,
};
int getchoice(char *greet,char *choices[],FILE *in, FILE*out);
int main()
{
int choice = 0;
FILE * in;
FILE * out;
struct termios its,newits;
in = fopen("/dev/tty","r");
out = fopen("/dev/tty","w");
if(!in||!out)
{
        fprintf(stderr,"fail to open /dev/tty\n");
        exit(1);
}

tcgetattr(fileno(in),&its);
newits=its;
newits.c_lflag &= ~ICANON;
newits.c_lflag &= ~ECHO;
newits.c_cc[VMIN] = 1;
newits.c_cc[VTIME] = 0;
newits.c_lflag &= ~ISIG;
if(tcsetattr(fileno(in),TCSANOW,&newits))
{
fprintf(stderr,"could not set attr\n");
}

if(!isatty(fileno(stdout)))
{
        fprintf(stderr,"You are not a terminal!\n");
//      exit(1);
}
do
{
choice=getchoice("please select an action",menu,in,out);//,out);
printf("you have chosen: %c\n",choice);

}while(choice != 'q');
tcsetattr(fileno(in),TCSANOW,&its);
exit(0);
}

int getchoice(char *greet,char *choices[],FILE * in,FILE *out)
{
int chosen = 0;
int selected;
char **option;
do{
        fprintf(out,"choice: %s\n",greet);
        option=choices;
        while(*option)  //print menu
        {
                //printf("%s\n",*option);
                fprintf(out,"%s\n",*option);
                option++;
        }
        do{
                selected = fgetc(in);

                //selected = getchar();
        }while(selected == '\n');//|| selected == '\r'); //encounter '\n' then loop on and on
        option = choices;
        while(*option)
        {
                if(selected == *option[0])
                {
                        chosen = 1;
                        break;
                }
                option++;
        }
        if(!chosen)
        {
                fprintf(out,"incorrect choice,select again\n");
        }
}while(!chosen);

return selected;
}
只要用户一键入字符就会立刻得到程序的响应,而且用户键入的字符不会回显。

【上篇】
【下篇】

抱歉!评论已关闭.