
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - fseek() 函式
C 庫的 fseek(FILE *stream, long int offset, int whence) 函式將流的檔案位置設定為給定的偏移量。此函式是 C 標準庫的一部分,用於檔案處理。
語法
以下是 C 庫 fseek() 函式的語法:
int fseek(FILE *stream, 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]
廣告