fseek函数的用法

对于c语言fseek函数在大一题库中有这样一道题:fseek(fp,100L,2)

int fseek( FILE *stream, long offset, int origin );
第一个参数stream为文件指针
第二个参数offset为偏移量,整数表示正向偏移,负数表示负向偏移
第三个参数origin设定从文件的哪里开始偏移,可能取值为:SEEK_CUR、 SEEK_END 或 SEEK_SET
SEEK_SET: 文件开头
SEEK_CUR: 当前位置
SEEK_END: 文件结尾
其中SEEK_SET,SEEK_CUR和SEEK_END和依次为0,1和2.
简言之:
fseek(fp,100L,0);把fp指针移动到离文件开头100字节处;
fseek(fp,100L,1);把fp指针移动到离文件当前位置100字节处;
fseek(fp,100L,2);把fp指针退回到离文件结尾100字节处。

具体实例如下

#include   
#define N 5  
typedef struct student {  
 long sno;  
 char name[10];  
 float score[3];  
} STU;  
void fun(char *filename, STU n)  
{  
 FILE *fp;  
 fp = fopen(filename, "rb+");  
 fseek(fp, -1L*sizeof(STU),SEEK_END);  
fwrite(&n, sizeof(STU), 1, fp);  
fclose(fp);  
}  
void main()  
{  
  STU t[N]={ {10001,"MaChao", 91, 92, 77}, {10002,"CaoKai", 75, 60, 88},  
  {10003,"LiSi", 85, 70, 78}, {10004,"FangFang", 90, 82, 87},  
  {10005,"ZhangSan", 95, 80, 88}};  
  STU n={10006,"ZhaoSi", 55, 70, 68}, ss[N];  
  int i,j; FILE *fp;  
  fp = fopen("student.dat", "wb");  
  fwrite(t, sizeof(STU), N, fp);  
  fclose(fp);  
  fp = fopen("student.dat", "rb");  
  fread(ss, sizeof(STU), N, fp);  
  fclose(fp);  
  printf("\nThe original data :\n\n");  
  for (j=0; j<N; j++)  
  {  
   printf("\nNo: %ld Name: %-8s Scores: ",ss[j].sno, ss[j].name);  
   for (i=0; i<3; i++)   
[cpp] view plain copy
 printf("%6.2f ", ss[j].score[i]);  
 printf("\n");  
}  
fun("student.dat", n);  
printf("\nThe data after modifing :\n\n");  
fp = fopen("student.dat", "rb");  
fread(ss, sizeof(STU), N, fp);  
fclose(fp);  
for (j=0; j<N; j++)  
{  
 printf("\nNo: %ld Name: %-8s Scores: ",ss[j].sno, ss[j].name);  
 for (i=0; i<3; i++)   
[cpp] view plain copy
 printf("%6.2f ", ss[j].score[i]);  
 printf("\n");  
}  

你可能感兴趣的:(fseek函数的用法)