Namespaces
Variants

std:: ftell

From cppreference.net
< 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> の公開メンバ関数)