C 庫 - fseek() 函式



C 庫的 fseek(FILE *stream, long int offset, int whence) 函式將流的檔案位置設定為給定的偏移量。此函式是 C 標準庫的一部分,用於檔案處理。

語法

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

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

引數

此函式接受三個引數:

  • FILE *stream: 指向 FILE 物件的指標,用於標識流。
  • long int offset: 要移動檔案指標的位元組數。
  • int whence: 新增偏移量的起始位置。它可以具有以下值之一
    • SEEK_SET: 檔案開頭。
    • SEEK_CUR: 檔案指標的當前位置。
    • SEEK_END: 檔案結尾。

    返回值

    函式在成功時返回 0,失敗時返回非零值。該函式還會設定 errno 以指示錯誤。


    示例 1:移動到檔案開頭

    此程式開啟一個檔案,並在讀取第一個字元之前將檔案指標移動到檔案開頭。

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


    #include <stdio.h>
    
    int main() {
       FILE *file = fopen("example1.txt", "r");
       if (file == NULL) {
           perror("Error opening file");
           return 1;
       }
    
       fseek(file, 0, SEEK_SET);
    
       char ch = fgetc(file);
       if (ch != EOF) {
           printf("First character in the file: %c\n", ch);
       }
    
       fclose(file);
       return 0;
    }
    

    輸出

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

    First character in the file: [First character of the file]
    

    示例 2:從當前位置向後移動

    在此示例中,我們將檔案指標移動到從開頭算起的第 10 個位元組,然後將其向後移動 3 個位元組,導致檔案指標位於第 7 個位元組,從中讀取字元。


    #include <stdio.h>
    
    int main() {
       FILE *file = fopen("example3.txt", "r");
       if (file == NULL) {
           perror("Error opening file");
           return 1;
       }
    
       fseek(file, 10, SEEK_SET);  // Move to the 10th byte from the beginning
       fseek(file, -3, SEEK_CUR);  // Move 3 bytes backward from the current position
    
       char ch = fgetc(file);
       if (ch != EOF) {
           printf("Character after moving backward: %c\n", ch);
       }
    
       fclose(file);
       return 0;
    }
    

    輸出

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

    Character after moving backward: [Character at position 7]
    
    廣告