《程序设计基础-c语言》杨莉 刘鸿翔
ISBN-978-7-03-032903-5
p257
习题8
8.编写程序创建一个通讯录文件,在其中存入10
位同学的姓名、年龄、电话号码,并在屏幕上输出第2
、4
、6
、8
、10
位同学的信息
#include
#include
#define SIZE 10
struct student
{
char name[20];
int age;
char phone[20];
}stu[SIZE];
int main()
{
FILE *fp;
int i;
printf("输入%d位学生的姓名、年龄、电话:(eg:hzz 21 17683866724)\n",SIZE);
for(i=0;i<SIZE;i++)
{
scanf("%s %d %s",stu[i].name,&stu[i].age,stu[i].phone);
}
if((fp=fopen("phone.txt","wb"))==NULL)
{
printf("error\n");
exit(0);
}
for(i=0;i<SIZE;i++)
{
if(fwrite(&stu[i],sizeof(struct student),1,fp)!=1)
{
printf("write error\n");
exit(0);
}
}
fclose(fp);
if((fp=fopen("phone.txt","rb"))==NULL)
{
printf("error\n");
exit(0);
}
for(i=0;i<SIZE;i+=2)
{
fseek(fp,i*sizeof(struct student),0);
fread(&stu[i],sizeof(struct student),1,fp);
printf("%s\t%d\t%s\n",stu[i].name,stu[i].age,stu[i].phone);
}
fclose(fp);
}