| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 405 人关注过本帖
标题:关于C语言中“文件”的问题!
只看楼主 加入收藏
shangong
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2009-8-31
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:4 
关于C语言中“文件”的问题!
麻烦大家帮我看一下这个程序有什么问题,我的目的是将键盘输入的数据存在二进制文件中,然后再读出。
它一般是运行第1遍是结果是正确的,但第2遍结果就不对了,都是乱码,为什么呢?
对文件的操作很不熟练,请大家帮忙。
#include <stdio.h>
#define NULL 0
struct student{
 char name[10];
 int score;};
main()
{
 FILE *fp;
 struct student s[4],t[4];
 int i;
 fp=fopen("x.txt","wb");
 if(fp==NULL)
  printf("error!");
 for(i=0;i<4;i++)
 {
  scanf("%s%d",s[i].name,&s[i].score);
  fwrite(&s[i],sizeof(struct student),1,fp);
 }
 printf("the messages are:\n");
 printf("name    score\n");
 rewind(fp);
 for(i=0;i<4;i++)
  fread(&t[i],sizeof(struct student),1,fp);
 for(i=0;i<4;i++)
  printf("%-10s%d\n",t[i].name,t[i].score);
 fclose(fp);
}
搜索更多相关主题的帖子: 文件 C语言 
2009-08-31 20:07
西园竹
Rank: 5Rank: 5
等 级:职业侠客
帖 子:41
专家分:305
注 册:2009-8-8
收藏
得分:10 
先关闭文件然后再用只读的方式打开
或者用读写的方式打开,fp=fopen("x.txt","wb");最后的“wb”改为“wb+”
2009-08-31 20:27
UserYuH
Rank: 12Rank: 12Rank: 12
来 自:毅华
等 级:火箭侠
威 望:8
帖 子:720
专家分:3300
注 册:2009-8-10
收藏
得分:2 
楼上正解!

努力—前进—变老—退休—入土
2009-08-31 20:45
prankmoon
Rank: 8Rank: 8
等 级:蝙蝠侠
帖 子:161
专家分:921
注 册:2009-7-21
收藏
得分:8 
建议使用fseek,而不是rewind。原因如下:
The rewind function repositions the file pointer associated with stream to the beginning of the file. A call to rewind is similar to
 
(void) fseek( stream, 0L, SEEK_SET );
 
However, unlike fseek, rewind clears the error indicators for the stream as well as the end-of-file indicator. Also, unlike fseek, rewind does not return a value to indicate whether the pointer was successfully moved.
 
而对于fseek根据函数返回值就可以很容易地判断出指向文件开始:
If successful, fseek returns 0. Otherwise, it returns a nonzero value.

以上英文信息摘自MSDN。
2009-08-31 22:52
shangong
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2009-8-31
收藏
得分:0 
谢谢大家的帮助
2009-09-01 15:16
快速回复:关于C语言中“文件”的问题!
数据加载中...
 
   



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

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