C 庫 - ftell() 函式



C 庫的 ftell() 函式返回給定流的當前檔案位置。此函式對於確定檔案中的下一個讀或寫操作將發生的位置非常重要。

語法

以下是 C 庫 ftell() 函式的語法:

long ftell(FILE *stream);

引數

stream : 指向 FILE 物件的指標,指定檔案流。FILE 物件通常透過使用 fopen() 函式獲得。

返回值

成功時,ftell() 返回當前檔案位置作為長整數。失敗時,它返回 -1L 並設定全域性變數 errno 以指示錯誤。

示例 1

ftell() 的基本用法

在此示例中,我們開啟一個檔案,移動檔案位置指示器,然後使用 ftell() 獲取當前位置。

#include <stdio.h>
int main() {
   FILE *file = fopen("example.txt", "r");
   if (file == NULL) {
      perror("Failed to open file");
      return 1;
   }

   // Move the file position indicator to the 10th byte
   fseek(file, 10, SEEK_SET);

   // Get the current position
   long position = ftell(file);
   if (position == -1L) {
      perror("ftell failed");
   } else {
      printf("Current file position: %ld\n", position);
   }
   fclose(file);
   return 0;
}

輸出

以上程式碼產生以下結果:

Current file position: 10

示例 2

使用 ftell() 確定檔案長度

此示例演示如何使用 ftell() 透過查詢檔案末尾來查詢檔案的長度。

#include <stdio.h>
int main() {
   FILE *file = fopen("example.txt", "r");
   if (file == NULL) {
      perror("Failed to open file");
      return 1;
   }

   // Move the file position indicator to the end of the file
   fseek(file, 0, SEEK_END);

   // Get the current position, which is the file size
   long fileSize = ftell(file);
   if (fileSize == -1L) {
      perror("ftell failed");
   } else {
      printf("File size: %ld bytes\n", fileSize);
   }
   fclose(file);
   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

File size: 150 bytes
廣告

© . All rights reserved.