名前空間
変種
操作

std::fgetc, std::getc

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

指定された入力ストリームから次の文字を読み取ります。

目次

[編集] パラメータ

stream - 文字を読み取る対象

[編集] 戻り値

成功した場合は取得した文字、失敗した場合は EOF

失敗がファイルの終端条件によって引き起こされた場合、 additionally sets the eof indicator (see std::feof()) on stream. If the failure has been caused by some other error, sets the error indicator (see std::ferror()) on stream.

[編集]

#include <cstdio>
#include <cstdlib>
 
int main()
{
    int is_ok = EXIT_FAILURE;
    FILE* fp = std::fopen("/tmp/test.txt", "w+");
    if (!fp)
    {
        std::perror("File opening failed");
        return is_ok;
    }
 
    int c; // Note: int, not char, required to handle EOF
    while ((c = std::fgetc(fp)) != EOF) // Standard C I/O file reading loop
        std::putchar(c);
 
    if (std::ferror(fp))
        std::puts("I/O error when reading");
    else if (std::feof(fp))
    {
        std::puts("End of file reached successfully");
        is_ok = EXIT_SUCCESS;
    }
 
    std::fclose(fp);
    return is_ok;
}

出力

End of file reached successfully

[編集] 関連

(C++11で非推奨)(C++14で削除)
stdinから文字列を読み取る
(関数) [編集]
ファイルストリームに1文字書き込む
(関数) [編集]
ファイルストリームに1文字を戻す
(関数) [編集]
C ドキュメント for fgetc, getc
English 日本語 中文(简体) 中文(繁體)