iostream の状態について
書いとかないと忘れそうなのでメモ
gcc の basic_ios は以下のような operator void* と operator! を持っているので
//@{ /** * @brief The quick-and-easy status check. * * This allows you to write constructs such as * "if (!a_stream) ..." and "while (a_stream) ..." */ operator void*() const { return this->fail() ? 0 : const_cast<basic_ios*>(this); } bool operator!() const { return this->fail(); } //@}
以下のように
if (in.read(buf, size)) // operator void* { std::cout << "OK"; }
や、以下のように
if (!in.read(buf, size)) // operator! { std::cout << "NG"; }
のようなことができる。
内容は fail() が呼ばれているだけなので、以下のようなコードに等しい
in.read(buf, size); if (!in.fail()) { std::cout << "OK"; }
read の前に eof か判断したい時は、以下のように peek を取ってみるといい
if (in.peek() != std::istream::traits_type::eof()) { std::cout << "EOF"; }
最初、以下のようにやってて全然ダメだった
if (in.eof()) // これは eof フラグが立ったかを見るだけで、peek() が eof かどうかは関係ない { std::cout << "EOF"; }