Latest web development tutorials

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 w3cschool.cc", fp);
  
   fseek( fp, 7, SEEK_SET );
   fputs(" C Programming Langauge", fp);
   fclose(fp);
   
   return(0);
}

讓我們編譯並運行上面的程序,這將創建文件file.txt ,它的內容如下。 最初程序創建文件和寫入This is w3cschool.cc ,但是之後我們在第七個位置重置了寫指針,並使用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>