软件工程试验3

内部模块化的命令行菜单

SA17225400【哪来的妖精 + 《软件工程(C编码实践篇)》MOOC课程作业http://mooc.study.163.com/course/USTC-1000002006 】

试验内容:

将实验2的程序模块化。

将命令行抽象为一个数据结构struct.h.代码如下

typedef struct DataNode
{
    char*   cmd;   //命令
    char*   desc;  // 命令描述
    void     (*handler)();    // 命令函数指针
    struct  DataNode  *next;

} tDataNode;

将命令的声明单独写在头文件cmd.h,因为函数过于简单,直接在头文件里实现了,调用了一些shell命令,

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

void Help()
{
    printf("help version data ipconfig route ls netstat exit");
} ;

void Date()
{
    system("date");
};

void Ipconfig()
{
    system("ipconfig");
};

void Route()
{
    system("route");
};

void List()
{
    system("ls");
};

void Netstat()
{
    system("netstat");
};

void Exit()
{
    exit(0);
};

主程序cmd.c代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "struct.h"
#include "cmd.h"
#define CMD_MAX_LEN 128

static tDataNode head[] =
{
    {"help", "There are cmds you can input
", Help, &head[1]},
    {"version", "Menu Programe Version 1.0
" , NULL, &head[2]},
    {"date", "The date is: 
" , Date, &head[3]},
    {"ifconfig", "The IP state:
" , Ipconfig, &head[4]},
    {"route", "The route state:
" , Route, &head[5]},
    {"ls", "The file list:
" , List, &head[6]},
    {"netstat", "The Net state:
" , Netstat, &head[7]},
    {"exit", "The Programe will exit!" , Exit, NULL}
    
} ; 


int main()
{
    char cmd[CMD_MAX_LEN];
    
     while(1)
    {    
        printf("
Please input your cmd:
");
        scanf("%s",cmd);
        tDataNode *p = head;
        while(p != NULL)
        {
            if(strcmp(p->cmd, cmd) == 0)
            {
                printf("%s 
",  p->desc);
                if(p->handler != NULL)
                {
                    p->handler();
                }
                
                break;
            }
            p = p->next;
        }
        if(p == NULL)
        {
            printf("This is a wrong cmd!
");
        }
    }

    return 0;
}

程序运行截图:

提交GitHub:

试验总结:软件工程开—闭原则:对扩展开放,对修改关闭。以及利用程序模块化使得程序更具扩展性,提高可读性。

原文地址:https://www.cnblogs.com/raincute/p/7641241.html