1、P168
一个完整的终端输出选择菜单的程序。
#include
#include
#include
#include
#include
#include
#include
#include
#include
int getchoice(char* ,const char** ,FILE*,FILE*);
static FILE* output_stream=(FILE*)0;
char* opt[]=
{
"a -- add a new record",
"d -- delete a new record",
"q -- quit",
NULL
};
int char_to_terminal(int char_to_write)
{
if (output_stream)putc(char_to_write,output_stream);
return 0;
}
int getchoice(char* words,const char** opt,FILE* in,FILE* out)
{
int choice;
char** tmp_opt=opt;
int screenrow=4;
int screencol=10;
char *cursor,*clear;
output_stream=out;
while(1)
{
//将输出修改成清屏,然后左上角输出、
screenrow=4;
setupterm(NULL,fileno(out),(int *)0);
cursor=tigetstr("cup");
clear=tigetstr("clear");
tputs(clear,1,(int *)char_to_terminal);
tputs(tparm(cursor,screenrow,screencol),1,char_to_terminal);
fprintf(out,"Choice:\n");
screenrow+=2;
while(*tmp_opt)
{
tputs(tparm(cursor,screenrow,screencol),1,char_to_terminal);
fprintf(out,"%s\n", *tmp_opt );
tmp_opt++;
screenrow++;
}
fprintf(out,"\n" );
do
{
fflush(out);
choice=fgetc(in);
}while(choice=='\n' || choice=='\r');
tmp_opt=opt;
while(*tmp_opt)
{
if (choice==*tmp_opt[0])
{
return choice;
}
else{
tmp_opt++;
}
}
tputs(tparm(cursor,screenrow,screencol),1,char_to_terminal);
fprintf(stderr,"Incorrect choice,select again\n");
}
}
int main(int argc,char** argv)
{
int choice=0;
FILE* in=fopen("/dev/tty","r");
FILE* out=fopen("/dev/tty","w");
if(!in||!out)
{
fprintf(stderr, "%s\n", "Unable to open /dev/tty \n");
exit(1);
}
struct termios tmp_tos,back_tos;
tcgetattr(fileno(in),&tmp_tos);
back_tos=tmp_tos;
tmp_tos.c_lflag &= ~ICANON;
tmp_tos.c_lflag &= ~ECHO;
tmp_tos.c_lflag &= ~ISIG;
tmp_tos.c_cc[VMIN] = 1;
tmp_tos.c_cc[VTIME] = 0;
if (tcsetattr(fileno(in),TCSANOW,&tmp_tos)!=0)
{
fprintf(stderr, "%s\n", "Unable to set /dev/tty \n");
}
while(choice!='q')
{
choice=getchoice("Please select an action",opt,in,out);
fprintf(out,"You have choose: %c \n", choice);
sleep(1);
}
tcsetattr(fileno(in),TCSANOW,&back_tos);
return 0;
}
1、P171
一个检测击键事件的程序。
#include
#include
#include
#include
#include
#include
#include
#include
#include
static struct termios initsetting,newsetting;
void close_keybord();
void init_keybord();
int readch();
int kbhit();
int main(int argc,char** argv)
{
int choice=0;
init_keybord();
while(choice!='q')
{
printf("looping\n");
sleep(1);
if (choice=kbhit())
{
choice=readch();
printf("You have key: %c \n", choice);
}
}
close_keybord();
return 0;
}
void close_keybord()
{
tcsetattr(0,TCSANOW,&initsetting);
}
void init_keybord()
{
tcgetattr(0,&initsetting);
newsetting=initsetting;
newsetting.c_lflag &= ~ICANON;
newsetting.c_lflag &= ~ECHO;
newsetting.c_lflag &= ~ISIG;
newsetting.c_cc[VMIN] = 1;
newsetting.c_cc[VTIME] = 0;
tcsetattr(0,TCSANOW,&newsetting);
}
int readch(){
}
int kbhit(){
char ch;
int nread;
newsetting.c_cc[VMIN] = 0;
tcsetattr(0,TCSANOW,&newsetting);
nread=read(0,&ch,1);
newsetting.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&newsetting);
if (nread==1)
{
return ch;
}
return 0;
}