Understanding Unix/Linux Programming-用户程序:play_again1
2016-08-26 18:13
423 查看
1 /* play_again1.c 2 * purpuse: ask if user wants another play 3 * better : instant response without echo 4 * returns: 0 -> yes , 1 -> no 5 */ 6 7 #include <stdio.h> 8 #include <stdlib.h> 9 #include <termios.h> 10 11 #define QUESTION "Do you want another play?" 12 13 int get_response(char *); 14 void set_crmode(void); 15 void tty_mode(int); 16 17 int main() 18 { 19 int response ; 20 tty_mode(0); // save tty mode 21 set_crmode(); 22 response = get_response(QUESTION); 23 tty_mode(1); // restore tty mode 24 return response ; 25 } 26 27 int get_response(char * qiz) 28 { 29 int input ; 30 printf("%s(y/n)" , qiz); 31 while(1) 32 { 33 switch(input = getchar()) 34 { 35 case 'y': 36 case 'Y': 37 printf("\n"); 38 return 0 ; 39 case 'n': 40 case 'N': 41 case EOF: 42 printf("\n"); 43 return 1 ; 44 default : 45 printf("\nCannot understand %c" , input ); 46 printf("Please type y or no \n"); 47 } 48 } 49 } 50 51 void set_crmode(void) 52 { 53 struct termios ttystate ; 54 tcgetattr(0 , &ttystate); 55 ttystate.c_lflag &= ~ICANON ; // No Buffering 56 ttystate.c_cc[VMIN] = 1 ; //Get one char one time 57 tcsetattr( 0 , TCSANOW , &ttystate); 58 } 59 60 void tty_mode(int mode) 61 { 62 static struct termios original_mode ;// 设置静态结构体变量 63 if(mode == 0 ) 64 { 65 tcgetattr( 0 , & original_mode);// 存储原有设置 66 } 67 else 68 { 69 //还原原有设置 70 if( tcsetattr(0 , TCSANOW , & original_mode) == -1 ) 71 { 72 perror("Restore tty settings failed!\n"); 73 } 74 } 75 }
相关文章推荐
- Understanding Unix/Linux Programming-用户程序:play_again3
- Understanding Unix/Linux Programming-用户程序:play_again0
- Understanding Unix/Linux Programming-用户程序play_again4.c
- Understanding Unix/Linux Programming-用户程序:play_again2
- Understanding Unix/Linux Programming 笔记:chapter 8:进程和程序:编写命令解释器sh
- Understanding Unix/Linux Programming note:chapter 6:为用户编程:终端控制和信号
- Understanding Unix/Linux Programming-信号与play_again4.c的准备知识
- Understanding Unix/Linux Programming 笔记:chapter 12:连接和协议:编写Web服务器
- Understanding Unix/Linux Programming note:chapter 2, chapter 3, chapter 4
- Understanding Unix/Linux Programming-cp指令练习
- Understanding Unix/Linux Programming 笔记:chapter 7:事件驱动编程:编写一个视频游戏
- Understanding Unix/Linux Programming-事件驱动编程:编写一个视频游戏
- Understanding Unix/Linux Programming-pwd指令练习
- Understanding Unix/Linux Programming-ls指令练习一
- Understanding Unix/Linux Programming note:chapter 5:连接控制:学习stty
- Understanding Unix/Linux Programming-时钟编程:Alarms
- Understanding Unix/Linux Programming-终端控制和信号
- Understanding Unix/Linux Programming 笔记:chapter 9:可编程的shell、shell变量和环境; chapter 10:I/O重定向和管道
- Understanding Unix/Linux Programming-文件、设备和流
- Understanding Unix/Linux Programming note:chapter 1:执行可执行文件时的参数传递