august 发表于 2008-10-26 11:29:13

C语言读取文件的fseek的问题

用这样的结构
struct
{
    char name;
    long num;
    float score;
}stud;

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

然后通过fseek定位后读出一个数据,程序如下:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    struct
    {
      char name;
      long num;
      float score;
    }stud;
    FILE *fp;
    int rec_no;
    long offset;

    if((fp=fopen("c:\\file1","rb"))==NULL)
      exit(1);
    printf("enter record number that you want:");
   
   scanf("%d",&rec_no);                           //输入偏位几位
   offset = (rec_no-1)*sizeof(stud);          //得到偏移量
    if(fseek(fp,offset,0)!=0)                           //给fp定位
    {
      printf("can't move pointer there.\n");
      exit(1);
    }
    fread(&stud,sizeof(stud),1,fp);            //读取该位置上的内容
    printf("name:%s\n",stud.name);      //输出
    printf("num:%ld\n",stud.num);
    printf("score:%f\n",stud.score);
    fclose(fp);
    system("PAUSE");
    return 0;
}



为什么我输入6的时候,不会打印出printf("can't move pointer there.\n");这句话呢?

ravenex 发表于 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又想保证不超过文件尾,自己检查就是:
// long size; FILE* fp;

fseek(fp,0,SEEK_END);
size = ftell(fp);
fseek(fp,0,SEEK_SET);

// offset = (rec_no-1)*sizeof(stud);
if (offset >= size) {
    // ...
}
页: [1]
查看完整版本: C语言读取文件的fseek的问题