您的位置:首页 > 其它

二进制文件的读写

2016-03-08 16:35 183 查看
二进制文件的读写:

#include<stdio.h>

#include<string.h>

/*通讯录结构定义*/

int n=0;

struct friends_list{

char name[10]; /* 姓名 */

int age; /* 年龄 */

char telephone[13]; /* 联系电话 */

}friends[50];

void new_friend();

void show_friend();

int main(void)

{ int choice;

do{ printf("手机通讯录功能选项:1:新建 2:显示 0:退出\n");

printf("请选择功能:");

scanf("%d", &choice);

switch(choice)

{ case 1:

printf("新建联系人信息:");

new_friend("f1.dat");break;

case 2:

printf("显示联系人信息:");

show_friend("f1.dat"); break;

case 0: break;}

}while(choice!=0);

printf("谢谢使用通讯录功能!\n");

return 0;}

/*新建联系人*/

void new_friend(char *filename)

{ struct friends_list f;

FILE *fp,*p;

fp=fopen(filename,"ab");

printf("请输入新联系人的姓名:");

scanf("%s", f.name);

printf("请输入新联系人的年龄:");

scanf("%d", &f.age);

printf("请输入新联系人的联系电话:");

scanf("%s", f.telephone);

fwrite(&f,sizeof(f),1,fp);

fclose(fp) ;

p=fopen("f.txt","r");

fscanf(p,"%d",&n);printf("\n%d",n);

fclose(p);

n++;

p=fopen("f.txt","w");

fprintf(p,"%d",n);

fclose(p);

}

void show_friend(char *filename)

{ int i=0;

FILE *fp,*p;

p=fopen("f.txt","r");

fscanf(p,"%d",&n);

fclose(p);

fp = fopen(filename, "rb");

printf("\nname age telephone\n");

while(i<n)

{ fread(&friends[i],sizeof(struct friends_list),1,fp);

printf("%-10s %3d %-13s\n",friends[i].name ,friends[i].age,friends[i].telephone);i++;}

fclose(fp) ;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: