名稱空間
變體
操作

ftell

來自 cppreference.com
< c‎ | io
 
 
檔案輸入/輸出
型別和物件
        
函式
檔案訪問
(C95)
非格式化輸入/輸出
(C95)(C95)
(C95)
(C95)(C95)
(C95)
(C95)

格式化輸入
 
定義於標頭檔案 <stdio.h>
long ftell( FILE* stream );

返回檔案流 stream 的檔案位置指示器。

如果流以二進位制模式開啟,此函式獲得的值是從檔案開頭算起的位元組數。

如果流以文字模式開啟,此函式返回的值是未指定的,並且僅作為 fseek() 的輸入才有意義。

目錄

[編輯] 引數

stream - 要檢查的檔案流

[編輯] 返回值

成功時返回檔案位置指示器,失敗時返回 -1L

錯誤時,errno 變數被設定為實現定義的正值。

[編輯] 注意

在 Windows 上,可以使用 _ftelli64 來處理大於 2 GiB 的檔案。

[編輯] 示例

演示帶有錯誤檢查的 ftell()。向檔案寫入並讀取一些浮點(FP)值。

#include <stdio.h>
#include <stdlib.h>
 
/* If the condition is not met then exit the program with error message. */
void check(_Bool condition, const char* func, int line)
{
    if (condition)
        return;
    perror(func);
    fprintf(stderr, "%s failed in file %s at line # %d\n", func, __FILE__, line - 1);
    exit(EXIT_FAILURE);
}
 
int main(void)
{
    /* Prepare an array of FP values. */
    #define SIZE 5
    double A[SIZE] = {1.1, 2.0, 3.0, 4.0, 5.0};
 
    /* Write array to a file. */
    const char* fname = "/tmp/test.bin";
    FILE* file = fopen(fname, "wb");
    check(file != NULL, "fopen()", __LINE__);
 
    const int write_count = fwrite(A, sizeof(double), SIZE, file);
    check(write_count == SIZE, "fwrite()", __LINE__);
 
    fclose(file);
 
    /* Read the FP values into array B. */
    double B[SIZE];
    file = fopen(fname, "rb");
    check(file != NULL, "fopen()", __LINE__);
 
    long int pos = ftell(file); /* position indicator at start of file */
    check(pos != -1L, "ftell()", __LINE__);
    printf("pos: %ld\n", pos);
 
    const int read_count = fread(B, sizeof(double), 1, file); /* read one FP value */
    check(read_count == 1, "fread()", __LINE__);
 
    pos = ftell(file); /* position indicator after reading one FP value */
    check(pos != -1L, "ftell()", __LINE__);
    printf("pos: %ld\n", pos);
    printf("B[0]: %.1f\n", B[0]); /* print one FP value */
 
    return EXIT_SUCCESS;
}

可能的輸出

pos: 0
pos: 8
B[0]: 1.1

[編輯] 參考

  • C23 標準 (ISO/IEC 9899:2024)
  • 7.21.9.4 ftell 函式 (p: TBD)
  • C17 標準 (ISO/IEC 9899:2018)
  • 7.21.9.4 ftell 函式 (p: TBD)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.21.9.4 ftell 函式 (p: 337-338)
  • C99 標準 (ISO/IEC 9899:1999)
  • 7.19.9.4 ftell 函式 (p: 303-304)
  • C89/C90 標準 (ISO/IEC 9899:1990)
  • 4.9.9.4 ftell 函式

[編輯] 另請參閱

獲取檔案位置指示器
(函式) [編輯]
將檔案位置指示器移動到檔案中特定位置
(函式) [編輯]
將檔案位置指示器移動到檔案中特定位置
(函式) [編輯]
C++ 文件 關於 ftell