- 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 庫 - ftell() 函式
C 庫的 ftell() 函式返回給定流的當前檔案位置。此函式對於確定檔案中的下一個讀或寫操作將發生的位置非常重要。
語法
以下是 C 庫 ftell() 函式的語法:
long ftell(FILE *stream);
引數
stream : 指向 FILE 物件的指標,指定檔案流。FILE 物件通常透過使用 fopen() 函式獲得。
返回值
成功時,ftell() 返回當前檔案位置作為長整數。失敗時,它返回 -1L 並設定全域性變數 errno 以指示錯誤。
示例 1
ftell() 的基本用法
在此示例中,我們開啟一個檔案,移動檔案位置指示器,然後使用 ftell() 獲取當前位置。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
// Move the file position indicator to the 10th byte
fseek(file, 10, SEEK_SET);
// Get the current position
long position = ftell(file);
if (position == -1L) {
perror("ftell failed");
} else {
printf("Current file position: %ld\n", position);
}
fclose(file);
return 0;
}
輸出
以上程式碼產生以下結果:
Current file position: 10
示例 2
使用 ftell() 確定檔案長度
此示例演示如何使用 ftell() 透過查詢檔案末尾來查詢檔案的長度。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
// Move the file position indicator to the end of the file
fseek(file, 0, SEEK_END);
// Get the current position, which is the file size
long fileSize = ftell(file);
if (fileSize == -1L) {
perror("ftell failed");
} else {
printf("File size: %ld bytes\n", fileSize);
}
fclose(file);
return 0;
}
輸出
執行以上程式碼後,我們得到以下結果:
File size: 150 bytes
廣告