|
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <termios.h>
- #include <term.h>
- #include <curses.h>
- static FILE *output_stream = (FILE *)0;
- char *menu[] = {
- "a - add new record",
- "d - delete record",
- "q - quit",
- NULL,
- };
- int getchoice(char *greet, char *choices[], FILE *in, FILE *out);
- int char_to_terminal(int char_to_write);
- int main()
- {
- int choice = 0;
- FILE *input;
- FILE *output;
- if(!isatty(fileno(stdout))) {
- fprintf(stderr, "you are not a terminal, OK.\n");
- }
- input = fopen("/dev/tty", "r");
- output = fopen("/dev/tty", "w");
- if(!input || !output) {
- fprintf(stderr, "Unable to open /dev/tty\n");
- exit(1);
- }
- do {
- choice = getchoice("Please select an action", menu, input, output);
- printf("You have chosen: %c\n", choice);
- sleep(2);
- } while(choice != 'q');
- exit(0);
- }
- int getchoice(char *greet, char *choices[], FILE *in, FILE *out)
- {
- int chosen = 0;
- int selected;
- int screenrow, screencol = 10;
- char **option;
- char *cursor, *clear;
- output_stream = out;
- setupterm(NULL, fileno(out), (int *)0);/*设置终端*/
- cursor = tigetstr("cup"); /*得到光标位置转义序列*/
- clear = tigetstr("clear"); /*得到clear清屏转义序列*/
- screenrow = 4;
- tputs(clear, 1, char_to_terminal);/*清屏*/
- tputs(tparm(cursor, screenrow, screencol), 1, char_to_terminal);/*定位光标*/
- fprintf(out, "choice: %s", greet);
- screenrow += 2;
- option = choices;
- while(*option) { /*打印菜单,每次换行都需设置一次*/
- tputs(tparm(cursor, screenrow, screencol), 1, char_to_terminal);
- fprintf(out, "%s", *option);
- screenrow++;
- option++;
- }
- fprintf(out, "\n");
- do {
- fflush(out); /*清缓冲区*/
- selected = fgetc(in);
- option = choices;
- while(*option) { /*检查输入选项*/
- if(selected == *option[0]) {
- chosen = 1;
- break;
- }
- option++;
- }
- if(!chosen && selected != '\n') { /*遇到回车符不打印出错信息*/
- tputs(tparm(cursor, screenrow, screencol), 1, char_to_terminal);
- fprintf(out, "Incorrtct choice, select again\n");
- }
- } while(!chosen);
- tputs(clear, 1, char_to_terminal);
- return selected;
- }
- /*构造 putchar() 型函数,putc() 相当于 putchar()*/
- int char_to_terminal(int char_to_write)
- {
- if(output_stream) putc(char_to_write, output_stream);
- return 0;
- }
复制代码
对于函数“char_to_terminal”的调用一直有点疑问,定义char_to_terminal的时候是int char_to_terminal (int char_to_write),但是在调用的时候并没有给赋值给char_to_write这个形参。 |
|