本文主要是介绍c语言,功能简单的电话簿,实现输入,显示,查找的功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
感谢论坛里给我提供建议和意见的人,是你们的陪伴让我在风雨中前行,谢谢你们
特别感谢@NeilHappy ,@codesnail ,@xiakan008 ,你们对程序的完善提供的建设性的指导意见
c代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN sizeof(struct mystr)
void main()
{struct mystr{char name[40];char add[100];char code[20];char tel[20];struct mystr *next;};FILE *fp;struct mystr *head,*p1,*p2;char select,useless,search_name[40];int out_err_flag=0,search_flag=0;if((fp=fopen("phonebook.txt","ab+"))==NULL){printf("File open error!\n");exit(0);}/*SELECT MENU*/printf("1.Insert a new record\n2.Display existed records\n");printf("3.Search a record\nELSE Quit\nPlease give your choice:");scanf("%c%c",&select,&useless);/*select is 1, insert a new record*/if(select=='1'){printf("NOTE: Use # to finish input\n");p1=p2=(struct mystr *)malloc(LEN);head=p1;head->next=NULL;do{printf("Input the name:");gets(p1->name);if(strcmp(p1->name,"#")==0) break;printf("Input the address:");gets(p1->add);if(strcmp(p1->add,"#")==0) break;printf("Input the post code:");gets(p1->code);if(strcmp(p1->code,"#")==0) break;printf("Input the telphone number:");gets(p1->tel);if(strcmp(p1->tel,"#")==0) break;/*write to phonebook.txt*/if(fwrite(p1,LEN,1,fp)==0) out_err_flag=1;p1=(struct mystr *)malloc(LEN);p2->next=p1;p2=p1;}while(1);printf("With a '#', you have ended the input\n");if(out_err_flag==1)printf("Errors ocure when writing to file!\n");}/*select is 2, display existed records*/else if(select=='2'){printf("NAME\tADD\tCODE\tTEL\n");p1=(struct mystr *)malloc(LEN);while(!feof(fp)){if(fread(p1,LEN,1,fp))printf("%s\t%s\t%s\t%s\n",p1->name,p1->add,p1->code,p1->tel);}free(p1);}/*select is 3, do research*/else if(select=='3'){printf("Support search by name, please give a name:");gets(search_name);p1=(struct mystr *)malloc(LEN);while(!feof(fp)){if(fread(p1,LEN,1,fp))if(strcmp(p1->name,search_name)==0){printf("NAME\tADD\tCODE\tTEL\n");printf("%s\t%s\t%s\t%s\n",p1->name,p1->add,p1->code,p1->tel);search_flag=1;}}if(search_flag!=1)printf("Nothing matched!\n");free(p1);}/*if select is anything else, quit*/else exit(0);fclose(fp);getch();
}
这篇关于c语言,功能简单的电话簿,实现输入,显示,查找的功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!