【正确答案】①#include"stdio.h"
main()
{
FILE*fp;
char ch,fname[20];
printf("please input file name:\n");
scanf("/%s",fname);
if((fp=fopen(fname,"w"))==NULL)
{
printf("cannot open this file!\n");
exit(0);
}
printf("please input some text:\n");
ch=getchar();
while((ch=getchar())!='$')
fputc(ch,fp);
fclose(fp);
printf("\nthe content ofthe file/%s is:\n",fname);
if((fp=fopen(fname,"r"))==NULL)
{
printf("cannot open this file!\n");
exit(0);
}
while(!feof(fp))
{
ch=fgetc(fp);
putchar(ch);
}
fclose(fp);
}
②#include"stdio.h"
main()
{
struct person{
char name[20];
char sex;
int age;
float height;
}personl;
FILE*fp;
char fname[20];
int i;
printf("please input a file name:\n");
scanf("/%s",fname);
if((fp=fopen(fname,"wb"))==NULL)
{
printf("cannot open this file!\n");
exit(0);
}
printf("please input thlee persons'name,sex,age and height:\n");
for(i=0;i<3;i++)
{
scant("/%s/%c/%d/%f",person1.name,&person1.sex,&person1.age,&person1.height);
if(fwrite(&person1,sizeof(person1),1,fp)!=1)
{
prinff("write error!\n");
exit(0);
}
fclose(fp);
if((fp=fopen(fname,"lb"))==NULL)
{
printf("cannot open this file!\n");
exit(0);
}
printf("\nthe content ofthe file is:\nName\t\tSex\tAge\tHeight\n");
while(!feof(fp))
{
if(fread(&person1,sizeof(personl),1,fp)==1)
printf("/%-16s/%-8c/%-8d/%-10.2f\n",person1.name,person1.sex,person1.age,person 1.height);
}
fclose(fp);
}
③#include"stdio.h"
main()
{
struc t person
{char name[20];
char sex:
int age;
float height;
}person1;
FILE*fp;
char fname[20];
int i;
printf("please input a file name:\n");
scanf("/%s",fname);
if((fp=fopen(fname,"wb"))==NULL)
{
printf("cannot open this file!\n");
exit(0);
}
printf("please input three persons'name,sex,age and height:\n");
for(i=0;i<3;i++)
{
scanf("/%s /%c/%d/%f",person1.name, &person1.sex, &person1.age,&person 1.height);
if(fwrite(&person1,sizeof(personl),1,fD)!=1)
{
printf("write error!\n");
exit(0);
}
}
fclose(fp);
if((fp=fopen(fname,"rb"))==NULL)
{
printf("cannot open this file!\n");
exit(0);
}
printf("please input the sequence number(0、1 or 2):\n");
scanf("/%d",&i);
printf("\nthe information about this person is:\nName\t\tSex\lAge\tHeight\n");
fseek(fp,i*sizeof(person1),0);
if(fread(&person1,sizeof(person1),1,fp)==1)
printf("/%-16s/%-8c/%-8d/%-10.2f\n",person1.name,person1.sex,person1.age,person 1.height);
fclose(fp);
}
【答案解析】