- 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 庫 - 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
廣告