不管编写什么软件,我们都会涉及到模块的编写。说是模块,其实就是管理一片资源,这些资源的概念很广,可以是内存、锁、socket、字符串、文件、空间大小等等。所以不管是什么模块,你需要注意下面几个方面,当然这也是给外界提供的基本接口函数。
(1)模块初始化
(2)申请模块资源
(3)获取模块资源
(4)释放模块资源
(5)查找模块资源
(6)显示模块资源
为了说明问题,我们可以用一个mailist来说明一个简单的模块应该怎么设计。当然,朋友们可以选择其他的功能进行实现。模块的功能虽然比较少,但是可以说明很多问题,大家可以多多练习。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#define STATUS int
#define OK 0
#define ERROR -1
#define MAX_RECORD_NUMBER 100
#define MAX_NAME_LEN 32
#define PHONE_NUMBER 9
struct TELEPH_MAIL_LIST
{
char name[MAX_NAME_LEN];
int phone[PHONE_NUMBER];
};
static struct TELEPH_MAIL_LIST g_mail_list[MAX_RECORD_NUMBER];
void module_init()
{
memset(g_mail_list, 0, sizeof(g_mail_list));
}
struct TELEPH_MAIL_LIST* alloc_record()
{
int index;
for(index = 0; index < MAX_RECORD_NUMBER; index++)
{
if(0 == strlen(g_mail_list[index].name))
{
return &g_mail_list[index];
}
}
return NULL;
}
void del_record(struct TELEPH_MAIL_LIST* p_mail_list)
{
if(p_mail_list < 0 || p_mail_list >= &g_mail_list[MAX_RECORD_NUMBER])
{
return;
}
memset(p_mail_list, 0, sizeof(struct TELEPH_MAIL_LIST));
}
int find_record(char* name)
{
int index;
for(index = 0; index < MAX_RECORD_NUMBER; index++)
{
if(0 == strncmp(g_mail_list[index].name, name, MAX_NAME_LEN))
{
return index;
}
}
return ERROR;
}
STATUS add_record(char* name, int phone[])
{
struct TELEPH_MAIL_LIST* p_mail_list;
if(ERROR != find_record(name))
{
return ERROR;
}
p_mail_list = alloc_record();
if(NULL == p_mail_list)
{
return ERROR;
}
strncpy(p_mail_list->name, name, strlen(name));
memmove(p_mail_list->phone, phone, sizeof(int) * PHONE_NUMBER);
return OK;
}
void show_record()
{
int index ;
int number;
for(index = 0; index < MAX_RECORD_NUMBER; index ++)
{
if(0 == strlen(g_mail_list[index].name))
{
continue;
}
printf("[name] : %s\n", g_mail_list[index].name);
printf("[phon] : ");
for(number = 0; number < PHONE_NUMBER; number ++)
{
printf("%d", g_mail_list[index].phone[number]);
}
printf("\n");
}
}
int main(int argc, char* argv[])
{
struct TELEPH_MAIL_LIST* p_mail_list;
int phone[] = {1,2,3,4,5,6,7,8,9};
module_init();
add_record("hello", phone);
show_record();
del_record(&g_mail_list[find_record("hello")]);
show_record();
return 1;
}