设为首页 加入收藏

TOP

菜鸟修炼C语言小设计之――通讯录(二)(一)
2014-11-23 23:55:17 来源: 作者: 【 】 浏览:44
Tags:菜鸟 修炼 语言 设计 通讯录

通讯录在通讯录(一)的基础上作了一些完善,添加了保存联系人的功能。

主要涉及的C语言重要知识点有:

文件流的操作

代码:

main.c

#include

#include "record.h"

int menu_select(void);

void hand_menu(int cmd, int *flag);

int main(int argc, char *argv[])

{

int cmd = 0;

int flag = 1;

while(1){

cmd = menu_select();

if(cmd == '0')

return 0;

hand_menu(cmd, &flag);

}

}

int menu_select(void)

{

int select;

printf(" <------通信薄-------->\n");

printf("1:添加联系人 2:删除联系人\n");

printf("3:显示所有联系人 4:保存\n");

printf("0:退出\n");

printf("请输入:\n");

select = getch();

while(select < '0'|| select>'4') {

printf("输入错误,请重新输入:\n");

select = getch();

}

return select;

}

void hand_menu(int cmd, int *flag)

{

static ADDR *list_head = NULL;

if(1 == *flag){

list_head = init_person(list_head);

*flag = 0;

}

switch(cmd){

case '1':

list_head = add_person(list_head);

break;

case '2':

list_head = del_person(list_head);

break;

case '3':

dis_person(list_head);

break;

case '4':

save_person(list_head);

break;

default:

break;

}

}

record.h

#ifndef _RECORD_H_

#define _RECORD_H_

typedef struct{

char name[8];

char tel[20];

}DATA;

typedef struct node{

DATA data;

struct node *next;

}ADDR;

#define ASK(p) do{\

p = (ADDR *)malloc(sizeof(ADDR));\

if(p==NULL){printf("malloc memory failed!");exit(-1);}\

}while(0)

#endif

opre.c

#include

#include "record.h"

#define FILE_NAME "phonebook.dat"

ADDR* add_person(ADDR *list_head)

{

ADDR *head = list_head;

ADDR *node = list_head;

ADDR *new_p;

ASK(new_p);

new_p->next = NULL;

printf("请输入姓名:");

scanf("%s", new_p->data.name);

printf("请输入电话号码:");

scanf("%s", new_p->data.tel);

if(!node){

head = new_p;

return head;

}

while(node->next)

node=node->next;

node->next = new_p;

return head;

}

ADDR *del_person(ADDR *list_head)

{

ADDR *node = list_head;

ADDR *head = list_head;

char name[8];

ADDR *pre = node;

printf("请输入要删除的名字:");

scanf("%s", name);

if(!strcmp(head->data.name, name)){

pre = head;

head = head->next;

free(pre);

return head;

}

while(node){

if(!strcmp(node->data.name, name)){

pre->next = node->next;

free(node);

printf("成功删除!\n");

return;

}

pre = node;

node = node->next;

}

printf("没有找到该名字!\n");

return head;

}

void dis_person(ADDR *list_head)

{

ADDR *node = list_head;

if(!node)

return;

printf("姓名 号码\n");

while(node){

printf("%s %s\n", node->data.name, node->data.tel);

node = node->next;

}

}

void save_person(ADDR *list_head)

{

FILE *pf;

ADDR *node = list_head;

pf = fopen(FILE_NAME, "w+");

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇菜鸟修炼C语言小设计之――学生成.. 下一篇#include 和 在FileView中添加工..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: