名稱空間
變體
操作

std::ftell

來自 cppreference.com
< cpp‎ | io‎ | c
 
 
 
 
定義於標頭檔案 <cstdio>
long ftell( std::FILE* stream );

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

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

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

目錄

[編輯] 引數

stream - 要檢查的檔案流

[編輯] 返回值

成功時返回檔案位置指示器,失敗時返回 -1L。失敗時也會設定 errno

[編輯] 注意

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

[編輯] 示例

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

#include <cstdio>
#include <cstdlib>
#include <iostream>
 
// 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;
    std::perror(func);
    std::cerr << func << " failed in file " << __FILE__ << " at line # " << line - 1
              << '\n';
    std::exit(EXIT_FAILURE);
}
 
int main()
{
    // Prepare an array of FP values.
    constexpr int SIZE {5};
    double A[SIZE] = {1.1, 2.2, 3.3, 4.4, 5.5};
 
    // Write array to a file.
    const char* fname = "/tmp/test.bin";
    FILE* file = std::fopen(fname, "wb");
    check(file != NULL, "fopen()", __LINE__);
 
    const int write_count = std::fwrite(A, sizeof(double), SIZE, file);
    check(write_count == SIZE, "fwrite()", __LINE__);
 
    std::fclose(file);
 
    // Read the FP values into array B.
    double B[SIZE];
    file = std::fopen(fname, "rb");
    check(file != NULL, "fopen()", __LINE__);
 
    long pos = std::ftell(file); // position indicator at start of file
    check(pos != -1L, "ftell()", __LINE__);
    std::cout << "pos: " << pos << '\n';
 
    const int read_count = std::fread(B, sizeof(double), 1, file); // read one FP value
    check(read_count == 1, "fread()", __LINE__);
 
    pos = std::ftell(file); // position indicator after reading one FP value
    check(pos != -1L, "ftell()", __LINE__);
    std::cout << "pos: " << pos << '\n';
    std::cout << "B[0]: " << B[0] << '\n'; // print one FP value
 
    return EXIT_SUCCESS;
}

可能的輸出

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

[編輯] 參閱

獲取檔案位置指示器
(函式) [編輯]
將檔案位置指示器移動到檔案中特定位置
(函式) [編輯]
將檔案位置指示器移動到檔案中特定位置
(函式) [編輯]
返回輸入位置指示符
(std::basic_istream<CharT,Traits> 的公開成員函式) [編輯]
返回輸出位置指示器
(std::basic_ostream<CharT,Traits> 的公開成員函式) [編輯]
C 文件 關於 ftell