通讯录在通讯录(一)的基础上作了一些完善,添加了保存联系人的功能。
主要涉及的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)#endifopre.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+"); while(node){ fprintf(pf, "%s %s\n", node->data.name, node->data.tel); node = node->next; } fclose(pf); printf("保存成功!\n");}ADDR *init_person(ADDR *list_head){ ADDR *node = list_head; ADDR *head = list_head; ADDR *new_node; FILE *pf; char name[8]; char tel[20]; ASK(new_node); pf = fopen(FILE_NAME, "r"); if(!fscanf(pf, "%s%s", new_node->data.name, new_node->data.tel)){ free(new_node); return head; } rewind(pf); while(fscanf(pf, "%s%s", name, tel) == 2){ ASK(new_node); new_node->next = NULL; strcpy(new_node->data.name, name); strcpy(new_node->data.tel, tel); if(!head) node = head = new_node; else{ while(node->next) node = node->next; node->next = new_node; } } return head;}