C 庫 - fgetpos() 函式



C 庫的 fgetpos(FILE *stream, fpos_t *pos) 函式獲取流的當前檔案位置,並將其寫入 pos。它將位置儲存在一個 fpos_t 型別的變數中。當您需要儲存檔案中的特定位置並在以後返回到該位置時,此函式很有用。

語法

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

int fgetpos(FILE *stream, fpos_t *pos);

引數

此函式接受兩個引數:

  • FILE *stream: 指向 FILE 物件的指標,用於標識流。
  • fpos_t *pos: 指向 fpos_t 型別物件的指標,儲存位置。

返回值

fgetpos() 函式在成功時返回 0,失敗時返回非零值。

示例 1:簡單的獲取位置

此示例演示如何獲取並列印檔案中的當前位置。

以下是 C 庫 fgetpos() 函式的示例。

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "w+");
   if (file == NULL) {
       perror("Failed to open file");
       return 1;
   }

   fputs("Hello, World!", file);
   fpos_t pos;
   
   // Get the current file position
   if (fgetpos(file, &pos) != 0) {
       perror("fgetpos failed");
       fclose(file);
       return 1;
   }
   
   printf("Current position: %ld\n", (long)pos);

   fclose(file);
   return 0;
}

輸出

以上程式碼將“Hello, World!”寫入檔案並獲取位置,該位置為 13,因為“Hello, World!”包括空格和標點符號在內共有 13 個字元。

Current position: 13

示例 2:在檔案中讀取和倒回

在此示例中,它演示瞭如何從檔案中讀取資料、儲存位置,然後倒回到儲存的位置。

#include <stdio.h>

int main() {
   FILE *file = fopen("example3.txt", "w+");
   if (file == NULL) {
       perror("Failed to open file");
       return 1;
   }

   fputs("Line 1\nLine 2\nLine 3\n", file);
   fpos_t pos;
   
   // Rewind to the start of the file
   rewind(file);
   
   char buffer[20];
   fgets(buffer, sizeof(buffer), file);
   printf("First read: %s", buffer);
   
   // Save the current position after reading the first line
   if (fgetpos(file, &pos) != 0) {
       perror("fgetpos failed");
       fclose(file);
       return 1;
   }
   
   fgets(buffer, sizeof(buffer), file);
   printf("Second read: %s", buffer);
   
   // Return to the saved position
   if (fsetpos(file, &pos) != 0) {
       perror("fsetpos failed");
       fclose(file);
       return 1;
   }
   
   fgets(buffer, sizeof(buffer), file);
   printf("Re-read after fsetpos: %s", buffer);

   fclose(file);
   return 0;
}

輸出

執行以上程式碼後,它將多行寫入檔案,讀取第一行,儲存位置,讀取第二行,然後返回到儲存的位置並再次讀取第二行。

First read: Line 1
Second read: Line 2
Re-read after fsetpos: Line 2
廣告

© . All rights reserved.