名前空間
変種
操作

std::ftell

From cppreference.com
< cpp‎ | io‎ | c
 
 
 
C形式I/O
型とオブジェクト
関数
ファイルアクセス
直接入出力
非書式化入出力
書式付き入力
(C++11)(C++11)(C++11)    
(C++11)(C++11)(C++11)    
書式付き出力
ファイルポジショニング
ftell
エラーハンドリング
ファイル操作
 
ヘッダ<cstdio>で定義
long ftell( std::FILE* stream );

ストリームstreamのファイル位置指示子の現在の値を返します。

ストリームがバイナリモードで開かれている場合、この関数で得られる値はファイルの先頭からのバイト数です。

ストリームがテキストモードで開かれている場合、この関数が返す値は未定義であり、std::fseekへの入力としてのみ意味があります。

目次

[編集] パラメータ

stream - 調べるファイルストリーム

[編集] 戻り値

成功した場合はファイル位置指示子、失敗した場合は-1L。失敗した場合はerrnoも設定されます。

[編集] 備考

Windowsでは、2 GiBを超えるファイルを扱うには、_ftelli64を使用できます。

[編集]

エラーチェック付きの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> の public メンバ関数) [編集]
出力位置インジケータを返す
(std::basic_ostream<CharT,Traits> の public メンバ関数) [編集]
English 日本語 中文(简体) 中文(繁體)