曲径通幽论坛
标题:
菜单函数以及终端控制
[打印本页]
作者:
beyes
时间:
2009-3-13 22:28
标题:
菜单函数以及终端控制
测试代码
:
#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
;
}
运行及输出
:
为了看清每次的选择后再清屏就用了 sleep() 函数进行 2s 的延迟。
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/)
Powered by Discuz! X3.2