您的位置:首页 > 运维架构 > Linux

Linux终端编程--判断是否为终端

2015-09-28 21:05 676 查看
干货,代码贴出来:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

char *menu[] =
{
"a - add new record",
"d - delete record",
"q -quit",
NULL,
};

int getchoice(char *greet, char *choicess[]);

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();
option = choices;
}while(selected =='\n');
while(*option)
{
if (selected == *option[0])
{
chosen = 1;
break;
}
option++;
}
if(!chosen)
{
printf("Incorrect choice, select again \n");
}
}
while(!chosen);
return selected;

}执行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: