title: fstream EOF unexpectedly throwing exception
body: <p>My question is very similar to <a href="https://stackoverflow.com/questions/6781545/why-is-failbit-when-eof-on-read-is-there-a-way-out/">a previous one</a>.  I want to open and read a file.  I want exceptions thrown if the file can't be opened, but I don't want exceptions thrown on EOF.  fstreams seem to give you independent control over whether exceptions are thrown on EOF, on failures, and on other bad things, but it appears that EOF tends to also get mapped to the bad and/or fail exceptions.</p>
  
  <p>Here's a stripped-down example of what I was trying to do. The function f() is supposed to return true if a file contains a certain word, false if it doesn't, and throw an exception if (say) the file doesn't exist.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;string&gt;
  
  using namespace std;
  
  bool f(const char *file)
  {
      ifstream ifs;
      string word;
  
      ifs.exceptions(ifstream::failbit | ifstream::badbit);
      ifs.open(file);
  
      while(ifs &gt;&gt; word) {
          if(word == "foo") return true;
      }
      return false;
  }
  
  int main(int argc, char **argv)
  {
      try {
          bool r = f(argv[1]);
          cout &lt;&lt; "f returned " &lt;&lt; r &lt;&lt; endl;
      } catch(...) {
          cerr &lt;&lt; "exception" &lt;&lt; endl;
      }
  }
  </code></pre>
  
  <p>But it doesn't work, because basic fstream reading using operator>> is evidently one of the operations for which EOF sets the bad or the fail bit.  If the file exists and does not contain "foo" the function does not return false as desired, but rather throws an exception.</p>