幻想森林

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 3175|回复: 1

[通用编程] C语言读取文件的fseek的问题

[复制链接]

313

主题

1574

帖子

1万

积分

⑧专业

*永恒国度*

积分
14145
QQ
发表于 2008-10-26 11:29:13 | 显示全部楼层 |阅读模式
用这样的结构
struct
{
    char name[20];
    long num;
    float score;
}stud;

用fwrite 读入了三个数据
zhang shan
89101
89.5
---------------
li si
89102
90.5
---------------
wang wu
89103
71.5

然后通过fseek定位后读出一个数据,程序如下:
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. int main()
  4. {
  5.     struct
  6.     {
  7.         char name[20];
  8.         long num;
  9.         float score;
  10.     }stud;
  11.     FILE *fp;
  12.     int rec_no;
  13.     long offset;
  14.     if((fp=fopen("c:\\file1","rb"))==NULL)
  15.         exit(1);
  16.     printf("enter record number that you want:");
  17.    
  18.      scanf("%d",&rec_no);                             //输入偏位几位
  19.      offset = (rec_no-1)*sizeof(stud);          //得到偏移量
  20.     if(fseek(fp,offset,0)!=0)                             //给fp定位
  21.     {
  22.         printf("can't move pointer there.\n");
  23.         exit(1);
  24.     }
  25.     fread(&stud,sizeof(stud),1,fp);            //读取该位置上的内容
  26.     printf("name:%s\n",stud.name);        //输出
  27.     printf("num:%ld\n",stud.num);
  28.     printf("score:%f\n",stud.score);
  29.     fclose(fp);
  30.     system("PAUSE");
  31.     return 0;
  32. }
复制代码

为什么我输入6的时候,不会打印出printf("can't move pointer there.\n");这句话呢?
[img][/img] http://shop33698673.taobao.com被别人嫉妒,证明你优秀,嫉妒别人说明你无能
回复

使用道具 举报

0

主题

25

帖子

254

积分

③业余

积分
254
发表于 2008-10-26 15:36:12 | 显示全部楼层
本来就不会出错吧,虽然是rb方式打开的文件。
The End-of-File internal indicator of the stream is cleared after a call to this function, and all effects from previous calls to ungetc are dropped.
要用fseek又想保证不超过文件尾,自己检查就是:
  1. // long size; FILE* fp;
  2. fseek(fp,0,SEEK_END);
  3. size = ftell(fp);
  4. fseek(fp,0,SEEK_SET);
  5. // offset = (rec_no-1)*sizeof(stud);
  6. if (offset >= size) {
  7.     // ...
  8. }
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|幻想森林

GMT+8, 2024-4-19 06:32 , Processed in 0.016534 second(s), 21 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表