您的位置:首页 > 移动开发 > 微信开发

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

2017-10-09 15:13 429 查看
【网易云课堂昵称:zhangxuri198 + 《软件工程(C编码实践篇)》MOOC课程作业http://mooc.study.163.com/course/USTC-1000002006 】

实验要求:

注意代码的业务逻辑和数据存储之间的分离,即将系统抽象为两个层级:菜单业务逻辑和菜单数据存储;

要求:

1)遵守代码风格规范,参考借鉴代码设计规范的一些方法;

2)代码的业务逻辑和数据存储使用不同的源文件实现,即应该有2个.c和一个.h作为接口文件。

[b]实验过程:[/b]

在项目文件夹下建立lab3文件夹,并在文件夹下建立menu.c,linklist.c,linklist.h三个文件;

文件内容如下(代码见文末);

menu.c:用于存放数据和主方法



linklist.c:用于存放其他方法



linklist.h:用作接口文件,并存放结构体



实验结果:



PUSH:



(附)测试用代码:git clone https://git.coding.net/zhangxuri198/E1.git cd E1
cd lab3
gcc menu.c linklist.c -o menu
./menu
可使用测试命令:
help
version
quit

心得与感悟:

程序设计不仅仅要实现代码所追求的功能,还要为以后的维护和扩展做好准备。模块化思想可以很大程度的提升程序的可扩展性和可维护性,也会提升代码的内聚性,降低耦合度,时的程序的安全性稳定性提高。

代码:

menu.c:#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"
#include <string.h>

int Help();
int Quit();

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

static tDataNode head[] =
{
{"help","this is help cmd!",Help,&head[1]},
{"version", "menu program V1.0", NULL, &head[2]},
{"quit", "quit from menu!", Quit, NULL}
};

main()
{
while(1)
{
char cmd[CMD_MAX_LEN];
printf("Please print a cmd number > ");
scanf("%s", cmd);
tDataNode *p= FindCmd(head, cmd);
if(p == NULL)
{
printf("Thid is a wrong cmd!\n");
continue;
}
if(strcmp(cmd,p->cmd)==0)
{
printf("%s - %s\n", p->cmd, p->desc);
if(p->handler != NULL)
{
p->handler();
}
}
}
}

int Help()
{
ShowAllCmd(head);
return 0;
}
int Quit()
{
exit(0);
return 0;
}
linklist.c:
#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"
#include <string.h>

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

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐