“软件工程(C编码实践篇)”实验报告

实验三:内部模块化的命令行菜单小程序V2.0

实验三:内部模块化的命令行菜单小程序V2.0

【孙剑峰 SA16225264 + 《软件工程(C编码实践篇)》MOOC课程作业http://mooc.study.163.com/course/USTC-1000002006

代码地址: http://git.shiyanlou.com/csxiaoyao/shiyanlou_cs122/src/master/lab3

1. 实验要求

通过设计简单的命令行菜单小程序,了解并掌握程序内部模块化设计的思想,实现菜单数据存储与菜单业务逻辑的分离。

2. 实验思路

用一个静态链表来存储可变化的菜单命令及其对应函数,在主函数中实菜单命令逻辑。 在一个头文件中定义链表数据结构及其操作原型,并在相应源文件中实现其操作;然后在主函数源文件中实现菜单命令。

3. 实验过程

实验代码如下:

3.1 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);

3.2 linklist.c

#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"

tDataNode* FindCmd(tDataNode *head, char *cmd) {
    if (head == NULL || cmd == NULL)
        return NULL;
    tDataNode *p = head;
    while (p != NULL) {
        if (strcmp(cmd, p->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;
}

3.3 menu.c

#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"

#define CMD_MAX_LEN 128
#define DESC_LEN 1024
#define CMD_NUM 10

int Help();
int Quit();

/*menu program*/
static tDataNode head[] = {
    { "help","This is a help cmd.",Help,&head[1] },
    { "version","menu program v2.0.",NULL,&head[2] },
    { "quit","Quit form menu.",Quit,NULL }
};

int main() {
    /*cmd line begin*/
    while (1) {
        char cmd[CMD_MAX_LEN];
        printf("Please input a cmd:>");
        scanf("%s", cmd);
        tDataNode* p = FindCmd(head, cmd);
        if (p == NULL) {
            printf("This is a wrong cmd!");
            continue;
        }
        printf("%s - %s\n", p->cmd, p->desc);
        if (p->handler != NULL)
            p->handler();
    }
    return 0;
}

int Help() {
    ShowAllCmd(head);
    return 0;
}

int Quit() {
    exit(0);
}

4. 运行结果

图片描述

5. 实验总结

软件=程序+软件工程,程序=算法+数据结构
通过本次实验,我主要有以下几个方面的收获:

  1. 认识到模块化的重要性
  2. 了解了模块化程序设计的方法(KISS原则、设计与代码的一致性、不要和陌生人说话原则、用数据结构和控制结构来简化代码、错误处理)
  3. 程序的调试及维护
最新评论
暂无评论~