电子说
在嵌入式开发中,因为只有黑框框的终端,所以在终端输入指令是比较麻烦的,每次都需要重新实现解析字符串。
本篇文章分享一个自己常用的一套终端菜单系统。
代码如下:
#include
#include
#include
typedef enum CmdType
{
CMD1, CMD2, CMD3, CMD4, CMD5, QUIT
}CmdType;
typedef struct CmdList
{
CmdType type;
unsigned char info[50];
}CmdList;
CmdList g_cmd_list[] =
{
{CMD1, "run cmd1"},
{CMD2, "run cmd2"},
{CMD3, "run cmd3"},
{CMD4, "run cmd4"},
{CMD5, "run cmd5"},
{QUIT, "to quit"},
};
void printf_cmd_str()
{
int size = sizeof(g_cmd_list) / sizeof(g_cmd_list[0]);
printf("support cmd:\\n");
for (int i = 0; i < size; i++) {
printf(" .%d-->%s\\n", i, g_cmd_list[i].info);
}
printf("eg. you can input \\".0\\" to run this cmd.\\n");
}
int main(int argc, char *argv[])
{
int cmd_size = sizeof(g_cmd_list) / sizeof(g_cmd_list[0]);
while (1) {
printf_cmd_str();
char data[20] = {0};
if (fgets(data, 20, stdin) < 0) {
printf("fgets error\\n");
continue;
}
if (data[0] == '.') {
int id = atoi(&data[1]);
if (id >= cmd_size || id < 0) {
printf("input err\\n");
continue;
}
int cmd = g_cmd_list[id].type;
if (cmd == CMD1) {
printf("run cmd1\\n");
}
else if (cmd == CMD2) {
printf("run cmd2\\n");
}
else if (cmd == CMD3) {
printf("run cmd3\\n");
}
else if (cmd == CMD4) {
printf("run cmd4\\n");
}
else if (cmd == CMD5) {
printf("run cmd5\\n");
}
else if (cmd == QUIT) {
printf("to quit\\n");
break;
}
else {
printf("this cmd is not supported\\n");
}
}
else {
printf("input invalid\\n");
}
}
return 0;
}
运行结果如下:
****@****:~/zcl$ ./a.out
support cmd:
.0-->run cmd1
.1-->run cmd2
.2-->run cmd3
.3-->run cmd4
.4-->run cmd5
.5-->to quit
eg. you can input ".0" to run this cmd.
.0
run cmd1
support cmd:
.0-->run cmd1
.1-->run cmd2
.2-->run cmd3
.3-->run cmd4
.4-->run cmd5
.5-->to quit
eg. you can input ".0" to run this cmd.
.5
to quit
****@****:~/zcl$
审核编辑:刘清
全部0条评论
快来发表一下你的评论吧 !