天天看點

函數fseek() 用法(轉)

在閱讀代碼時,遇到了很早之前用過的fseek(),很久沒有用了,有點陌生,寫出來以便下次查閱。

函數功能是把檔案指針指向檔案的開頭,需要包含頭檔案stdio.h

fseek   函數名: fseek   功 能: 重定位流上的檔案指針   用 法: int fseek(FILE *stream, long offset, int fromwhere);   描 述: 函數設定檔案指針stream的位置。如果執行成功,stream将指向以fromwhere為基準,偏移offset個字     節的位置。如果執行失敗(比如offset超過檔案自身大小),則不改變stream指向的位置。   傳回值: 成功,傳回0,否則傳回其他值。   fseek position the file position pointer for the file referenced by stream to the byte location calculated by offset.   程式例:   

  1. #include <stdio.h>  
  2.   long filesize(FILE *stream);  
  3.   int main(void)  
  4.   {  
  5.     FILE *stream;  
  6.     stream = fopen("MYFILE.TXT", "w+");  
  7.     fprintf(stream, "This is a test");  
  8.     printf("Filesize of MYFILE.TXT is %ld bytes\n", filesize(stream));  
  9.     fclose(stream);  
  10.     return 0;  
  11.   }  
  12.   long filesize(FILE *stream)  
  13.     long curpos, length;  
  14.     curpos = ftell(stream);  
  15.     fseek(stream, 0L, SEEK_END);  
  16.     length = ftell(stream);  
  17.     fseek(stream, curpos, SEEK_SET);  
  18.     return length;  

  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位元組處。   使用執行個體:

  1. #define N 5  
  2. typedef struct student {  
  3.  long sno;  
  4.  char name[10];  
  5.  float score[3];  
  6. } STU;  
  7. void fun(char *filename, STU n)  
  8. {  
  9.  FILE *fp;  
  10.  fp = fopen(filename, "rb+");  
  11.  fseek(fp, -1L*sizeof(STU),SEEK_END);  
  12. fwrite(&n, sizeof(STU), 1, fp);  
  13. fclose(fp);  
  14. }  
  15. void main()  
  16.   STU t[N]={ {10001,"MaChao", 91, 92, 77}, {10002,"CaoKai", 75, 60, 88},  
  17.   {10003,"LiSi", 85, 70, 78}, {10004,"FangFang", 90, 82, 87},  
  18.   {10005,"ZhangSan", 95, 80, 88}};  
  19.   STU n={10006,"ZhaoSi", 55, 70, 68}, ss[N];  
  20.   int i,j; FILE *fp;  
  21.   fp = fopen("student.dat", "wb");  
  22.   fwrite(t, sizeof(STU), N, fp);  
  23.   fclose(fp);  
  24.   fp = fopen("student.dat", "rb");  
  25.   fread(ss, sizeof(STU), N, fp);  
  26.   printf("\nThe original data :\n\n");  
  27.   for (j=0; j<N; j++)  
  28.    printf("\nNo: %ld Name: %-8s Scores: ",ss[j].sno, ss[j].name);  
  29.    for (i=0; i<3; i++)   

  1.  printf("%6.2f ", ss[j].score[i]);  
  2.  printf("\n");  
  3. fun("student.dat", n);  
  4. printf("\nThe data after modifing :\n\n");  
  5. fp = fopen("student.dat", "rb");  
  6. fread(ss, sizeof(STU), N, fp);  
  7. for (j=0; j<N; j++)  
  8.  printf("\nNo: %ld Name: %-8s Scores: ",ss[j].sno, ss[j].name);  
  9.  for (i=0; i<3; i++)