C 庫函數 - fseek()

C 標準庫 - <stdio.h> C 標準庫 - <stdio.h>

描述

C 庫函數 int fseek(FILE *stream, long int offset, int whence) 設置流 stream 的檔位置為給定的偏移 offset,參數 offset 意味著從給定的 whence 位置查找的位元組數。

聲明

下麵是 fseek() 函數的聲明。

int fseek(FILE *stream, long int offset, int whence)

參數

  • stream -- 這是指向 FILE 對象的指針,該 FILE 對象標識了流。
  • offset -- 這是相對 whence 的偏移量,以位元組為單位。
  • whence -- 這是表示開始添加偏移 offset 的位置。它一般指定為下列常量之一:
常量描述
SEEK_SET檔的開頭
SEEK_CUR檔指針的當前位置
SEEK_END檔的末尾

返回值

如果成功,則該函數返回零,否則返回非零值。

實例

下麵的實例演示了 fseek() 函數的用法。

#include <stdio.h>

int main ()
{
   FILE *fp;

   fp = fopen("file.txt","w+");
   fputs("This is xuhuhu.com", fp);

   fseek( fp, 7, SEEK_SET );
   fputs(" C Programming Langauge", fp);
   fclose(fp);

   return(0);
}

讓我們編譯並運行上面的程式,這將創建檔 file.txt,它的內容如下。最初程式創建檔和寫入 This is xuhuhu.com,但是之後我們在第七個位置重置了寫指針,並使用 puts() 語句來重寫檔,內容如下:

This is C Programming Langauge

現在讓我們使用下麵的程式查看上面檔的內容:

#include <stdio.h>

int main ()
{
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1)
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
          break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}

C 標準庫 - <stdio.h> C 標準庫 - <stdio.h>