Namespaces
Variants

std:: fgetc, std:: getc

From cppreference.net
< cpp ‎ | io ‎ | c
ヘッダーで定義 <cstdio>
int fgetc ( std:: FILE * stream ) ;
int getc ( std:: FILE * stream ) ;

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

目次

パラメータ

stream - 文字を読み取るストリーム

戻り値

成功時に取得された文字、または EOF 失敗時。

失敗がファイル終端状態によって引き起こされた場合、追加で eof インジケータを設定する( std::feof() 参照)。 stream に対して。失敗が他のエラーによって引き起こされた場合、 error インジケータを設定する( std::ferror() 参照)。 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で削除)
標準入力から文字列を読み込む
(関数)
ファイルストリームに文字を書き込む
(関数)
ファイルストリームに文字を戻す
(関数)
Cドキュメント for fgetc , getc