内部模块化的命令行菜单小程序

来源:互联网 发布:qa软件 编辑:程序博客网 时间:2024/06/07 10:23

实验内容

实现内部模块化的命令行菜单小程序,注意代码的业务逻辑和数据存储之间的分离,即将系统抽象为两个层级:菜单业务逻辑和菜单数据存储。

实验内容及截图
1 创建文件夹 mkdir lab3
2 menu.c文件

#include<stdio.h>#include<stdlib.h>#include "linklist.h"int menu();int quit();#define CMD_MAX_LEN 128#define DESC_LEN 1024#define CMD_NUM 10static tDataNode head[]={    //初始化赋值  链表    {"menu", "this is menu cmd!", menu, &head[1]},    {"version", "menu program v2.0", NULL, &head[2]},    {"quit", "quit from menu", quit, NULL}};int main(){    while(1)    {        char cmd[CMD_MAX_LEN];        printf("Please input a cmd number ->");        scanf("%s",cmd);        tDataNode *p = FindCmd(head, cmd);        if(p == NULL)        {            printf("This is a wrong cmd!\n");            continue;        }        printf("%s - %s\n", p->cmd, p->desc);        if(p->handler != NULL)        {            p->handler();        }    }}int menu(){    ShowAllCmd(head);    return 0;}int quit(){    exit(0);}

3 linklist.c文件

/*这是一个拆分模块程序 */tDataNode* FindCmd(tDataNode * head, char * cmd){    if(head == NULL || cmd == NULL)    {        return NULL;    }    tDataNode *p = head;    while(p != NULL)    {        if(strcmp(p->cmd, cmd) == 0)        {            //作比较            return p;        }        p = p->next;    }    return NULL;}int ShowAllCmd(tDataNode * head){    printf("Menu List:\n");    tDataNode *p = head;    while(p != NULL)    {        printf("%s - %s\n", p->cmd, p->desc);        p = p->next;    }    return 0;}

4 linklist.h文件

//这是一个头文件//数据结构的定义typedef struct DataNode{    char * cmd;    char * desc;    int (*handler)();   //函数指针    struct DataNode * next;}tDataNode;//方法声明tDataNode * FindCmd(tDataNode * head, char * cmd);int ShowAllCmd(tDataNode * head);

5 编译

gcc menu.c linklist.c -o menu

6 运行

C:\Users\Je-vie\Desktop\workspace\lab3menu

7 效果

Please input a cmd number ->menumenu - this is menu cmd!Menu List:menu - this is menu cmd!version - menu program v2.0quit - quit from menuPlease input a cmd number ->versionversion - menu program v2.0Please input a cmd number ->quitquit - quit from menu

8 提交Github

在实验开始时候就已经在自己的git账号上创建一个lab3的仓库
并且clone到本地

λ git clone https://github.com/Je-vie/lab3
C:\Users\Je-vie\Desktop\workspace\lab3λ lsREADME.md  lab3  linklist.c  linklist.h  menu.c  menu.exe

所以最后直接提交

C:\Users\Je-vie\Desktop\workspace\lab3λ git add menu.c linklist.h linklist.cλ git commit -m"模块化设计"[master 23be817] 模块化设计 3 files changed, 118 insertions(+) create mode 100644 linklist.c create mode 100644 linklist.h create mode 100644 menu.cλ git pushUsername for 'https://github.com': je-viePassword for 'https://je-vie@github.com':Counting objects: 5, done.Delta compression using up to 4 threads.Compressing objects: 100% (5/5), done.Writing objects: 100% (5/5), 1.50 KiB | 0 bytes/s, done.Total 5 (delta 0), reused 0 (delta 0)To https://github.com/Je-vie/lab3   991f396..23be817  master -> master

9 实验总结
模块化设计是程序设计很重要的思想,在今后的开发中要不断思考

阅读全文
0 0