发布网友 发布时间:2024-03-17 06:25
共1个回答
热心网友 时间:2024-03-23 02:23
#include <stdio.h> #include <stdlib.h> #include <string.h> #define szSTR 64 #define fileDB "c:\\contact.txt" struct CONTACT { char name[szSTR];/*姓名*/ char unit[szSTR];/*工作单位*/ char tele[szSTR];/*电话*/ char mail[szSTR];/*mail*/ }; typedef struct CONTACT CON; #define BNAME 1 #define BUNIT 2 #define BTELE 4 #define BMAIL 8 #define BFULL 0xFF int OPER[5] = ; void input(CON * s, int mask) { if(mask & BNAME) if(mask & BUNIT) if(mask & BTELE) if(mask & BMAIL) }/*end input*/ void show (int id, CON * s) { if(!s) return ; if(id) printf("%d\t%s\t%s\t%s\t%s\n", id, s->name , s->unit , s->tele , s->mail ); else printf("%s%s%s%s\n", s->name , s->unit , s->tele , s->mail ); /*end if*/ }/*end show*/ void regist(void) { CON s; FILE * f = 0; input(&s, BFULL); f = fopen(fileDB, "ab"); fwrite(&s,sizeof(s),1,f); fclose(f); printf("资料已保存!\n"); }/*end regist*/ int browse(char * key, fpos_t * p, CON * s) { FILE * f =0; int i = 0, r = 0; CON t; char * a = 0, * b = 0; fpos_t q; if(!s) return 0; f = fopen(fileDB, "rb"); if(!f) { printf("数据库暂无记录\n"); return 0; }/*end if*/ printf("编号\t姓名\t单位\t电话\t电邮\n"); printf("------------------------------------------------\n"); while(!feof(f)) { fgetpos(f, &q); r = fread(&t, sizeof(t), 1, f); if(r<1)break; if(t.name[0]==0) continue; if(key) { a = strstr(t.name , key); b = strstr(t.tele , key); if(a == 0 && b == 0) continue; }/*end if*/ if(p) *p = q; if(s) memcpy(s, &t, sizeof(t)); i++; show(i, &t); }/*end while*/ fclose(f); printf("------------------------------------------------\n"); return i; }/*end browse*/ fpos_t query(CON * s) { char key[szSTR]=""; fpos_t p = 0; int r = 0; printf("请输入姓名或者电话号码:"); scanf("%s", key); r = browse(key, &p, s); return r?p:-1; }/*end query*/ void clear(void) { FILE * f = 0; CON s; fpos_t p = query(&s); if(p<0) return; f = fopen(fileDB, "rb+"); fsetpos(f, &p); memset(&s, 0, sizeof(s)); fwrite(&s, sizeof(s),1, f); fclose(f); printf("记录已删除!\n"); }/*end clear*/ void modify(void) { FILE * f = 0; CON s; int cmd = 0; fpos_t p = query(&s); if(p<0) return; f = fopen(fileDB, "rb+"); fsetpos(f, &p); for(;;) { show(0, &s); printf("请选择:1-姓名;2-工作单位;3-电话;4-电邮;5-保存并退出;6-放弃修改并退出\n"); scanf("%d", &cmd); switch(cmd) { case 1: case 2: case 3: case 4: input(&s, OPER[cmd]); break; case 5: fsetpos(f, &p); fwrite(&s, sizeof(s), 1, f); case 6: fclose(f); return; default: printf("错误的操作,请重新输入。\n"); }/*end case*/ }/*mext*/ }/*end clear*/ int main(void) { int cmd = 0; CON s; for(;;) { printf("欢迎使用通信簿!请选择:1-添加;2-查询;3-删除;4-修改;5-全部输出;0-退出\n"); scanf("%d", &cmd); switch(cmd) { case 0: return 0; case 1: regist(); break; case 2: query(&s); break; case 3: clear(); break; case 4: modify(); break; case 5: browse(0, 0, &s); break; }//end case } return 0; }