#include "通讯录啊.h"
int CheckCapacity(Address_Book** Book);
void Init(Address_Book** Book)
{
assert(Book);
(*Book)->capacity = INIT_CAPACITY;
(*Book)->num = 0;
memset((*Book)->book, 0, sizeof(Info) * (*Book)->capacity);
FILE* pf = fopen("Book.txt", "rb");
if (pf == NULL)
{
perror("Init");
printf(__LINE__);
return;
}
Info temp = { 0 };
while (fread(&temp, sizeof(Info), 1, pf))
{
if (0 == CheckCapacity(Book))
{
return;
}
(*Book)->book[(*Book)->num] = temp;
(*Book)->num++;
}
fclose(pf);
pf = NULL;
}
int CheckCapacity(Address_Book** Book)
{
assert(*Book);
if ((*Book)->num == (*Book)->capacity)
{
Address_Book* str = (Address_Book*)realloc(*Book, sizeof(Address_Book) + sizeof(Info) * ((*Book)->capacity + NEW_INIT_CAPACITY));
if (str == NULL)
{
printf("增容失败!\n");
return 0;
}
*Book = str;
(*Book)->capacity += NEW_INIT_CAPACITY;
printf("增容成功!!!\n");
return 1;
}
}
void Add_info(Address_Book** Book)
{
if (0 == CheckCapacity(Book))
{
return;
}
printf("请输入联系人姓名:\n");
scanf("%s", (*Book)->book[(*Book)->num].name);
printf("请输入联系人性别:\n");
scanf("%s", (*Book)->book[(*Book)->num].sex);
printf("请输入联系人年龄:\n");
scanf("%d", &(*Book)->book[(*Book)->num].age);
printf("请输入联系人电话:\n");
scanf("%s", (*Book)->book[(*Book)->num].telephone);
printf("请输入联系人地址:\n");
scanf("%s", (*Book)->book[(*Book)->num].address);
(*Book)->num++;
printf("添加成功!\n");
}
int True_False(Address_Book* Book, int* u_flag)
{
char name[20];
printf("输入联系人名字:\n");
scanf("%s", name);
for (int i = 0; i < Book->num; i++)
{
if (strcmp(name, Book->book[i].name) == 0)
{
*u_flag = i;
return 1;
}
}
return 0;
}
void Del_info(Address_Book** Book)
{
assert(*Book);
int u_flag = 0;
int ret = True_False(*Book, &u_flag);
if (ret == 1)
{
for (int i = u_flag; i < (*Book)->num; i++)
{
(*Book)->book[i] = (*Book)->book[i + 1];
}
printf("删除成功!\n");
}
else
{
printf("未查询到该联系人,删除失败!\n");
}
}
void Store(Address_Book** Book)
{
assert(*Book);
FILE* pf = fopen("Book.txt", "wb");
if (pf == NULL)
{
perror("Store");
return;
}
for (int i = 0; i < (*Book)->num; i++)
{
fwrite((*Book)->book + i, sizeof(Info), 1, pf);
}
fclose(pf);
pf = NULL;
}
void Search_info(Address_Book** Book)
{
assert(*Book);
int u_flag = 0;
int ret = True_False(*Book, &u_flag);
if (ret == 1)
{
printf("找到了:\n");
//打印信息
return;
}
printf("没找到!\n");
}
void Modify_info(Address_Book** Book)
{
assert(*Book);
int u_flag = 0;
int ret = True_False(*Book, &u_flag);
if (ret == 1)
{
printf("找到了:\n");
//修改信息
return;
}
printf("没找到!\n");
}
void Show_info(Address_Book** Book)
{
assert(*Book);
for (int i = 0; i < (*Book)->num; i++)
{
//打印信息
}
}
void Empty_info(Address_Book** Book)
{
assert(*Book);
memset((*Book)->book, 0, sizeof(Info) * (*Book)->num);
(*Book)->capacity = 0;
(*Book)->num = 0;
}
int cmp(void* p1, void* p2)
{
return strcmp(((Info*)p1)->name, ((Info*)p2)->name);
}
void Sort_info(Address_Book** Book)
{
assert(*Book);
//排序方式多种,可以Switch选择排序方式,这里名字排序
qsort((*Book)->book, (*Book)->num, sizeof(Info), cmp);
printf("排序完成!\n");
}