#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXL 120
typedef struct saddr {
char *name;
char *address;
char *zip;
char *phone;
struct saddr *next, *pre;
} ADDR;
char buffer[MAXL], fname[40];
FILE *fp;
int modified = 0;
ADDR *load();
void insert(), make(), find(), del(), display(), show(),
save(), freeall(), usage();
int getstr(FILE*, char **), getbuffer(FILE *);
int main(int argc, char **argv)
{
ADDR *head;
char c;
if (argc == 1) {
printf("请输入通信录文件名. ");
scanf("%s%*c", fname);
}
else{
strcpy(fname, *++argv);
}
head = load(fname);
while (1) {
printf("/n请输入命令: [i, f, d, s, q]/n");
while (getbuffer(stdin) == 0);
if ((c = buffer[0]) == 'q') {
if (modified) {
printf("修改后的通信录未保存,要保存吗?(y/n) ");
while (!(((c = getchar()) >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))continue;
if (c == 'y' || c == 'Y')
save(head, fname);
}
freeall(head);
break;
}
switch ? {
case 'i' :
insert(head);
break;
case 'f' :
find(head);
break;
case 'd' :
del(head);
break;
case 's' :
show(head);
break;
default :
usage();
break;
}
}//while (1)
return 0;
}//int main
/* 输入新的通信录 */
void insert( ADDR *ptr)
{
char *spt;
ADDR *p;
while (1) {
printf("名字? (立即回车表示结束) ");
if (getstr(stdin, &spt) ==0) break;
p = (ADDR *)malloc(sizeof(ADDR));
p->name = spt;
printf("地址? ");
getstr(stdin, &p->address);
printf("邮编? ");
getstr(stdin, &p->zip);
printf("电话号码? ");
getstr(stdin, &p->phone);
p->next = NULL;
p->pre = NULL;
make(ptr, p);
modified = 1;
}
}
/* 将*p插入链表 */
void make(ADDR *ptr, ADDR *p)
{
ADDR *pre, *suc;
pre = ptr;
suc = pre->next;
while (suc) {
if (strcmp(suc->name,p->name) >= 0) break;
pre = suc;
suc = pre->next;
}
pre->next = p;
p->pre = pre;
p->next = suc;
if(suc) suc->pre = p;
}
void find( ADDR *ptr )
{
ADDR *p;
printf("输入寻找的名: ");
while (getbuffer(stdin) == 0);
p = ptr->next;
while (p) {
if (strcmp(buffer, p->name) == 0) break;
p = p->next;
}
if (p)
display(p);
else
printf("末找到!/n");
}
/* 删除指定的通信录 */
void del( ADDR *ptr )
{
ADDR *pre, *suc;
printf("输入要删除的通信录的名: ");
while (getbuffer(stdin) == 0) ; /* 跳过空行 */
pre = ptr;
suc = pre->next;
while (suc) {
if (strcmp(suc->name, buffer) == 0) break;
pre = suc;
suc = pre->next;
}
if (suc) {
if (suc->next)
suc->next->pre = pre;
pre->next = suc->next;
free(suc->name);
free(suc->address);
free(suc->phone);
free(suc->zip);
free(suc);
modified = 1;
}
else
printf("Not found !/n");
}
void display( ADDR *ptr )
{
printf("/n/t名 : %s/n", ptr->name);
printf("/t地址 : %s/n", ptr->address);
printf("/t邮编 : %s/n", ptr->zip);
printf("/t电话 : %s/n", ptr->phone);
}
/* 告知命令用法 */
void usage()
{
printf("/n命令表:/n");
printf("i : 插入一条新的通信录./n");
printf("f : 按输入名寻找通信录./n");
printf("d : 按输入名删除一条通信录./n");
printf("s : 浏览通信录./n");
printf("q : 退出./n");