C 庫 - fsetpos() 函式



C 庫的 fsetpos() 函式將給定流的檔案位置設定為給定位置。引數 pos 是由 fgetpos 函式給出的位置。此函式是 <stdio.h> 庫的一部分,對於檔案的隨機訪問特別有用。

語法

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

int fsetpos(FILE *stream, const fpos_t *pos);

引數

此函式接受以下引數:

  • FILE *stream: 指向 FILE 物件的指標,標識該流。
  • const fpos_t *pos: 指向 fpos_t 物件的指標,包含新的位置。fpos_t 型別用於表示檔案位置。

返回值

fsetpos() 函式成功返回 0,出錯返回非零值。

示例 1

此示例演示在寫入檔案後將檔案位置設定為檔案開頭。

#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;
   fgetpos(file, &pos);  // Get the current position

   rewind(file);  // Set position to the beginning
   fsetpos(file, &pos);  // Set back to the saved position

   fputs(" Overwrite", file);

   fclose(file);
   return 0;
}

輸出

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

Hello, World! Overwrite

示例 2

使用 fsetpos() 移動到特定位置

此示例演示如何移動到檔案中的特定位置並修改內容。

#include <stdio.h>

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

   fputs("1234567890", file);

   fpos_t pos;
   fgetpos(file, &pos);  // Get the current position

   pos.__pos = 5;  // Set position to 5
   fsetpos(file, &pos);  // Move to position 5

   fputs("ABCDE", file);

   fclose(file);
   return 0;
}

輸出

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

12345ABCDE

示例 3

儲存和恢復檔案位置

此示例演示如何儲存檔案位置,執行某些操作,然後恢復原始位置。

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

   fputs("Original content", file);

   fpos_t pos;
   fgetpos(file, &pos);  // Save the current position

   fseek(file, 0, SEEK_END);  // Move to the end of the file
   fputs("\nNew content", file);

   fsetpos(file, &pos);  // Restore the original position
   fputs(" modified", file);

   fclose(file);
   return 0;
}

輸出

上述程式碼的輸出如下:

Original modified content
New content
廣告
© . All rights reserved.