linux命令行菜单

15 篇文章 0 订阅

linux命令行菜单

在嵌入式开发中,因为只有黑框框的终端,所以在终端输入指令是比较麻烦的,每次都需要重新实现解析字符串。
本篇文章分享一个自己常用的一套终端菜单系统。

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

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chasentech

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值