结构推理 文件
   1.实验目的
   ①掌握文件以及缓冲文件系统、文件指针的概念。
   ②学会使用文件打开、关闭、读、写等文件操作函数。
   ③学会用缓冲文件系统对文件进行简单的操作。
   2.实验内容
   编写程序并上机调试运行。
   ①编写建立一个文件,然后将从键盘输入的以“$”字符结尾的一般文本写入该文件并关闭该文件。然后重新打开该文件,将文件的内容读出并显示出来。
   ②从键盘输入3个人的自然情况信息,并将这些信息保存到一文件中。然后打开该文件,读出并显示该文件的内容。
   ③从键盘输入3个人的自然情况信息,并将这些信息保存到一个文件中。然后打开该文件,输入一个序号(0.1.2),并根据该序号读出并显示文件中这个人的信息。
【正确答案】①#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);
   }
【答案解析】