#include <string.h> /* strcpy */ #include <stdlib.h> /* malloc */ #include <stdio.h> /* printf */ #include "uthash.h" #define MAX_USERNAME_LEN (30) #define MAX_PHONENUM_LEN (30) #define ERROR_PARAMETER (-1) #define ERROR_USER_EXISTS (-2) #define ERROR_USER_NOT_EXISTS (-3) #define SUCCESS (0) typedef struct UserAndPhone { char userName[MAX_USERNAME_LEN]; char phoneNumber[MAX_PHONENUM_LEN]; }UserAndPhone; typedef struct PhoneBook { char userName[MAX_USERNAME_LEN]; /* key */ char phoneNumber[MAX_PHONENUM_LEN]; UT_hash_handle hh; /* makes this structure hashable */ }PhoneBook; PhoneBook* users = NULL; /* 用户及电话的哈希表 */ UserAndPhone* userAndPhone = NULL; /* 存放遍历的用户及电话 */ int userCnt = 0; /* 存放用户数 */ /******************************************************************* ****功 能:将新的用户、电话号码插入到哈希表 ****输入参数:phoneBook存放用户名、电话号码和哈希句柄,该参数由用户动态申请内存 ****返 回 值:-1参数错误,-2用户已存在、0添加成功 *******************************************************************/ int InsertUserAndPhone(PhoneBook* phoneBook) { if ((NULL == phoneBook) || (NULL == phoneBook->userName) || (NULL == phoneBook->phoneNumber) || (0 == strlen(phoneBook->userName)) || (0 == strlen(phoneBook->phoneNumber))) { printf("error parameter.\n"); return ERROR_PARAMETER; } PhoneBook* tmp; HASH_FIND_STR(users, phoneBook->userName, tmp); if (NULL != tmp) { printf("the userName[%s] already exist.\n", phoneBook->userName); return ERROR_USER_EXISTS; } HASH_ADD_KEYPTR(hh, users, phoneBook->userName, strlen(phoneBook->userName), phoneBook); ++userCnt; return SUCCESS; } /**************************************************************************************** ******功 能:根据用户名查找电话号码 ******输入参数:userName表示要查询的用户名 ****** phoneNumberFound 用来存放查找到的电话号码(由调用者保证空间足够大) ******返 回 值:-1参数错误,-3用户不存在,0找到 *****************************************************************************************/ int findPhoneNumber(char* userName, char *phoneNumberFound) { if ((NULL == userName) || (0 == strlen(userName)) || (NULL == phoneNumberFound)) { printf("invalid parameter.\n"); return ERROR_PARAMETER; } PhoneBook* tmp; HASH_FIND_STR(users, userName, tmp); if (NULL == tmp) { printf("the userName[%s] does not exist.\n", userName); return ERROR_USER_NOT_EXISTS; } else { strcpy(phoneNumberFound, tmp->phoneNumber); return SUCCESS; } }