| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 553 人关注过本帖
标题:在写文件后立即读时出错,见程序
取消只看楼主 加入收藏
csucsy
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2010-4-14
结帖率:50%
收藏
已结贴  问题点数:20 回复次数:1 
在写文件后立即读时出错,见程序
#include<stdio.h>
#include<stdlib.h>
#define SIZE 1
int main()
{
   struct student
   {  long number;
      char name[20];
      float score[3];
      float average;
   }stu[SIZE],stu1[SIZE];

   FILE *fp;
   int i,j;
   printf("Input the information of the students\n");
   for(i=0;i<SIZE;i++)
   {printf("No.%d:",i+1);
    scanf("%ld%s",&stu[i].number,stu[i].name);
    for(j=0;j<3;j++)
        scanf("%f",&stu[i].score[j]);
    stu[i].average=(stu[i].score[0]+stu[i].score[1]+stu[i].score[2])/3;
   }
   if((fp=fopen("file","wb"))==NULL)
   {printf("Cannot open the file");
   exit(0);
   }
   for(i=0;i<SIZE;i++)
       if(fwrite(&stu[i],sizeof(struct student),1,fp)!=1)
           printf("file write error");
   for(i=0;i<SIZE;i++)
   printf("%ld %s %4.1f %4.1f %4.1f %4.1f\n",stu[i].number,stu[i].name,stu[i].score[0],stu[i].score[1],
           stu[i].score[2],stu[i].average);
   fp=fopen("file","rb");
   for(i=0;i<SIZE;i++)
   {  fread(&stu1[i],sizeof(struct student),1,fp);
      printf("%ld %s %4.1f %4.1f %4.1f %4.1f\n",stu1[i].number,stu1[i].name,stu1[i].score[0],stu1[i].score[1],
           stu1[i].score[2],stu1[i].average);}
      fclose(fp);
}

搜索更多相关主题的帖子: long 
2011-03-02 21:49
csucsy
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2010-4-14
收藏
得分:0 
问题找到了,确实需要在写完之后要关闭文件,再读就没有问题了。用rewind()仍然有错。只是不太明白在对同一个文件操作为什么还要关闭文件。
2011-03-03 08:49
快速回复:在写文件后立即读时出错,见程序
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.046815 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved