【李文静《软件工程(C编码实践篇)》MOOC课程作业http://mooc.study.163.com/course/USTC-1000002006 】
实验思路
依然是命令行菜单小程序升级版,本次实验重点是模块化,简单的说就是将一个复杂的长程序,按照一定的规则拆分成多个小的程序,这样让代码更加可读,每个程序的功能更加明确。
主要代码
代码较长,仅列出部分
头文件link_list.h,包含一些宏定义和自定义的数据结构
#define CMD_NUM 8
#define CMD_MAX_LEN 128
#define CMD_ANNO_LEN 1024
// data structure:
typedef struct link_node {
char cmd_name[CMD_MAX_LEN];
char cmd_annotation[CMD_ANNO_LEN];
int (*handler)();
struct link_node* next;
} link_list;
link_list* search_cmd(char cmd[], link_list* head);
int show_all_cmd(link_list* head);
link_list.c 从原来的程序中划分出来的功能实现的子函数,包括将输入的命令与命令行对比和help菜单的展现
#include
#include
#include
#include "link_list.h"
link_list* search_cmd(char cmd[], link_list* head)
{
link_list* ptr = head;
if (cmd == NULL || ptr == NULL)
{
return NULL;
}
while (ptr != NULL)
{
if (strcmp(ptr->cmd_name, cmd) == 0)
{
break;
}
ptr = ptr->next;
}
return ptr;
}
int show_all_cmd(link_list* head)
{
printf("Your can see the command list of menu program:\n");
printf("----------------------------------------------\n");
link_list* ptr = head;
while (ptr != NULL)
{
printf("%s\t-\t%s\n", ptr->cmd_name, ptr->cmd_annotation);
ptr = ptr->next;
}
printf("----------------------------------------------\n");
return 0;
}
cmd_menu.c主函数 处理用户输入以及调用
#include
#include
#include
#include "link_list.h"
#define CMD_NUM 10
#define CMD_MAX_LEN 128
#define CMD_ANNO_LEN 1024
int cmd_help();
int cmd_version();
int cmd_quit();
int cmd_others();
int cmd_open();
int cmd_put();
int cmd_ls();
int cmd_close();
int cmd_cd();
int cmd_get();
static link_list head[] = {
{ "help", "you can see help list.", cmd_help, &head[1] },
{ "version", "menu program v2.0.4.", cmd_version, &head[2] },
{ "quit", "you quit the menu program.", cmd_quit, &head[3] },
{ "others", "This is 'others' command.", cmd_others, &head[4] },
{ "open", "This is 'open' command.", cmd_open, &head[5] },
{ "put", "This is 'put' command.", cmd_put, &head[6] },
{ "ls", "This is 'ls' command.", cmd_ls, &head[7] },
{ "close", "This is 'close' command.", cmd_close, &head[8] },
{ "cd", "This is 'cd' command.", cmd_cd, &head[9] },
{ "get", "This is 'get' command.", cmd_get, NULL }
};
int main()
{
char cmd[CMD_MAX_LEN];
while (true)
{
printf("please input your command > ");
scanf("%s", cmd);
link_list* ptr = search_cmd(cmd, head);
if (ptr == NULL)
{
printf("ERROR command: '%s'\n", cmd);
}
else
{
printf("%s\n", ptr->cmd_annotation);
ptr->handler();
}
}
return 0;
}
运行和结果
多个程序编译生成可执行文件的命令是:gcc cmd_menu.c link_list.c link_list,h -o cmd_menu
实验结果见截图四
实验总结
搜索了linux模块化编译c就会看到一个叫makefile的东西,这个程序使用makefile 编译也是很方便的。
使用makefile修改会比较方便,直接用make可以自动编译。只是这个程序涉及的文件还比较少,不太需要用到。