分类: LINUX
2008-12-04 16:12:41
实例:
# cat menu1.c
#include
#include
char *menu[] = {
"a - add new record",
"d - delete record",
"q - quit",
NULL,
};
int getchoice(char *greet, char *choices[]);
int main()
{
int choice = 0;
do
{
choice = getchoice("Please select an action", menu);
printf("You have chosen: %c\n", choice);
} while (choice != 'q');
exit(0);
}
int getchoice(char *greet, char *choices[])
{
int chosen = 0;
int selected;
char **option;
do {
printf("Choice: %s\n",greet);
option = choices;
while(*option) {
printf("%s\n",*option);
option++;
}
selected = getchar();
option = choices;
while(*option) {
if(selected == *option[0]) {
chosen = 1;
break;
}
option++;
}
if(!chosen) {
printf("Incorrect choice, select again\n");
}
} while(!chosen);
return selected;
}
运行结果:
# ./menu1
Choice: Please select an action
a - add new record
d - delete record
q - quit
a
a
You have chosen: a
Choice: Please select an action
a - add new record
d - delete record
q - quit
Incorrect choice, select again
Choice: Please select an action
a - add new record
d - delete record
q – quit
存在的问题,输入字母之后要按回车才行,不过程序同时又把回车当做字符来处理。
*
正规与非正规模式
canonical, or standard模式,按行来处理,以方便编辑。non-canonical模式,应用程序对字符的控制力变强。
上面字符后面实际跟的是换行符decimal 10, hex
上面的问题可以这样解决,今后会提供更完美的解决方法。
do {
selected = getchar();
} while(selected == ‘\n’);
*
重定向处理
通过查找终端相关的低级文件描述符可以确定标准输出是否被重定向。
#include
int isatty(int fd);
如果有打开文件标识符,则返回-1。如果发现被重定向,可以使用stderr,这个不会受shell重定向影响。
实例:
# cat menu2.c
#include
#include
#include
char *menu[] = {
"a - add new record",
"d - delete record",
"q - quit",
NULL,
};
int getchoice(char *greet, char *choices[]);
int main()
{
int choice = 0;
if(!isatty(fileno(stdout))) {
fprintf(stderr,"You are not a terminal!\n");
exit(1);
}
do
{
choice = getchoice("Please select an action", menu);
printf("You have chosen: %c\n", choice);
} while (choice != 'q');
exit(0);
}
int getchoice(char *greet, char *choices[])
{
int chosen = 0;
int selected;
char **option;
do {
printf("Choice: %s\n",greet);
option = choices;
while(*option) {
printf("%s\n",*option);
option++;
}
do{
selected = getchar();
} while (selected == '\n');
option = choices;
while(*option) {
if(selected == *option[0]) {
chosen = 1;
break;
}
option++;
}
if(!chosen) {
printf("Incorrect choice, select again\n");
}
} while(!chosen);
return selected;
}
执行结果:
# ./menu2 > file
You are not a terminal!
如果这样则不会有输出:
$ ./menu2 >file 2>file.error