std::basic_ios<CharT,Traits>::good
From cppreference.com
| bool good() const; |
||
ストリームに対する直近のI/O操作が正常に完了した場合、true を返します。具体的には、rdstate() = 0 の結果を返します。
ストリームの状態ビットを設定する条件のリストについては、ios_base::iostate を参照してください。
目次 |
[編集] パラメータ
(なし)
[編集] 戻り値
ストリームのエラーフラグがすべてfalseの場合、true を返します。それ以外の場合はfalse を返します。
[編集] 例
このコードを実行
#include <cstdlib> #include <fstream> #include <iostream> int main() { const char* fname = "/tmp/test.txt"; std::ofstream ofile{fname}; ofile << "10 " << "11 " << "12 " << "non-int"; ofile.close(); std::ifstream file{fname}; if (!file.good()) { std::cout << "#1. Opening file test.txt failed - " "one of the error flags is true\n"; return EXIT_FAILURE; } // typical C++ I/O loop uses the return value of the I/O function // as the loop controlling condition, operator bool() is used here for (int n; file >> n;) std::cout << n << ' '; std::cout << '\n'; if (file.bad()) { std::cout << "#2. I/O error while reading - badbit is true\n"; return EXIT_FAILURE; } else if (file.eof()) std::cout << "#3. End of file reached successfully - eofbit is true\n" "This is fine even though file.good() is false\n"; else if (file.fail()) std::cout << "#4. Non-integer data encountered - failbit is true\n"; }
実行結果の例
10 11 12 #4. Non-integer data encountered - failbit is true
[編集] 関連項目
basic_ios のアクセサ(good()、fail() など)が、ios_base::iostate フラグのすべての可能な組み合わせに対してどのような値を返すかを示す表を以下に示します。
| ios_base::iostate フラグ | basic_ios アクセサ | |||||||
eofbit
|
failbit
|
badbit
|
good() | fail() | bad() | eof() | operator bool | operator! |
| false | false | false | true | false | false | false | true | false |
| false | false | true | false | true | true | false | false | true |
| false | true | false | false | true | false | false | false | true |
| false | true | true | false | true | true | false | false | true |
| true | false | false | false | false | false | true | true | false |
| true | false | true | false | true | true | true | false | true |
| true | true | false | false | true | false | true | false | true |
| true | true | true | false | true | true | true | false | true |