C/C++ 中的 fseek()


fseek() 在 C 語言中用於將檔案指標移動到特定位置。偏移量和流是指標的目標,在函式引數中給出。如果成功,則返回零。如果不成功,則返回非零值。

以下是 fseek() 在 C 語言中的語法,

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

以下是 fseek() 中使用的引數

  • 流 − 這是用於標識流的指標。

  • 偏移量 − 這是從位置的位元組數。

  • 起始位置 − 這是新增偏移量的位置。

起始位置由以下常量之一指定。

  • SEEK_END − 檔案末尾。

  • SEEK_SET − 檔案開頭。

  • SEEK_CUR − 檔案指標的當前位置。

以下是在 C 語言中 fseek() 的示例。

假設我們有一個名為“demo.txt”的檔案,其內容如下 -

This is demo text!
This is demo text!
This is demo text!
This is demo text!

現在讓我們看看程式碼。

示例

#include<stdio.h>
void main() {
   FILE *f;
   f = fopen("demo.txt", "r");
   if(f == NULL) {
      printf("\n Can't open file or file doesn't exist.");
      exit(0);
   }
   fseek(f, 0, SEEK_END);
   printf("The size of file : %ld bytes", ftell(f));
   getch();
}

輸出

The size of file : 78 bytes

更新時間: 24-6-2020

1K+ 瀏覽次數

開始你的 職業生涯

完成該課程以獲得認證

開始吧
廣告