标题: 文件操作之-数据块读写fread(),fwrite()-C语言教程 [打印本页]

作者: 51黑ren    时间: 2015-12-20 03:06
标题: 文件操作之-数据块读写fread(),fwrite()-C语言教程
//向PC硬盘写入并读出两个学生信息fread(ElemType*,int Size,int n,FILE *)

//fwrite(ElemType*,int Size,int n,FILE *);参数:ElemType*--读写缓冲首指针   Size--数据块的大小
//  n--读写次数,FILE *--文件对象指针
//本例程包含文件检测部分内容

#include"stdio.h"
#include"stdlib.h"//用到了exit()
/*
fread():从指定文件读若干块数据

*/
struct  student
{
  char name[10];
  int age;
  float score;
};

void main()
{

  int i;
  student s1[2],s2[2],*p1,*p2;//s1和s2是两个结构体,s1用来存储键盘输入数据即写文件,s2用来存储读入数据
  FILE *fp;
  p1=s1;p2=s2;//给指针变量赋值
  if((fp=fopen("TEST2.txt","wt+"))==NULL)//“at”表示在fp文件末尾追加数据d:\\TEST.txt
  {
    printf("打开文件失败!");
        getchar();
        exit(1);

  }else
  {

         printf("请输入学生结构体信息数据:");
     printf("\n\r");

     for(i=0;i<2;i++)
         {
            scanf("%s %d %f",p1->name,&p1->age,&p1->score);//键盘输入结构体成员数据 &p1->name
                p1++;
         
         }
      p1=s1;
  //   fwrite(p1,sizeof(struct student),2,fp);//向fp文件写入数据块2次,每次写人一个结构体。即一共写入两个结构体数据块
         for(i=0;i<2;i++)//注意:这两种写入方式都可以
         {
             fwrite(p1,sizeof(struct student),1,fp);
             p1++;
         }

         //         p2=s2;
         /*“at”表示在fp文件末尾追加数据, 程序执行到此,文件内部指针已经指向文件末尾
           如果要读入fp文件的数据则必须将文件内部指针重新指向文件第一个字节处,即若要从文件第一个字节开始读数据
           就必须将文件内部指针重新rewind(fp)指向文件头
         
         */
         rewind(fp);


   printf("\n  \n");
   printf("读出的数据是:\n");
  // fread(p2,sizeof(struct student),2,fp);//向fp文件写入数据块2次,每次写人一个结构体。即一共写入两个结构体数据块
   for(i=0;i<2;i++)
         {
            fread(p2,sizeof(struct student),1,fp);
           printf("%s\n %d\n %f\n",p2->name,p2->age,p2->score);//分行显示
           p2++;
         }

  }
if(0==ferror(fp))printf("文件操作成功\n");//如果ferror(fp)返回值是0,表示文件操作没有出错
else printf("文件操作出错\n");
//判断文件内部指针是否结尾,如果feof(fp)返回值大于1则表示文件内部指针结尾
if(feof(fp)>1)printf("文件指针已结尾\n");
else printf("文件内部指针没有结尾\n");
char ch=fgetc(fp);//继续读出直到文件结尾
while(ch!=EOF)
{
   fgetc(fp);

}
if(feof(fp)>1)printf("文件指针已结尾\n");
else printf("文件内部指针没有结尾\n");
if(fclose(fp)==NULL)
  {
    printf("文件成功关闭!\n");

  }

}


///////////-----GKXW--------------////////////////////////////////////////











欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1