title: fstream !fail() and is_open()
body: <p>I want to write data to a file via <code>fstream</code> and output if <em>completely</em> (open-write-close) successful or not. I want also to write as few code as possible. It's about C++03.</p>
  
  <p>Solution1 (seems optimal):</p>
  
  <pre><code>std::fstream file;
  file.open("test.txt",std::ios_base::out); // sets failbit to true if open fails?
  file &lt;&lt; data; // what happens here if !file.is_open()?
  file.close(); // and here? does close() work when writing data failed?
  if (file)
      std::cout &lt;&lt; "Success";
  else
      std::cout &lt;&lt; "Failed";
  
  file.clear(); // for again usage. But what happens if file failed to open?
                // Or data failed to be written? Or file failed to be closed?
                // Is data waiting in stream to be written to next opened file?
  </code></pre>
  
  <p>Solution2:</p>
  
  <pre><code>std::fstream file;
  file.open("test.txt",std::ios_base::out);
  if (file.is_open())
  {
      file &lt;&lt; data;
      file.close();
  }
  if (file) // if only writing data fails, is failbit reset by close()?
      std::cout &lt;&lt; "Success";
  else
      std::cout &lt;&lt; "Failed";
  
  file.clear();
  </code></pre>
  
  <p>Solution3:</p>
  
  <pre><code>// is this solution overkill?
  
  std::fstream file;
  file.open("test.txt",std::ios_base::out);
  if (file.is_open())
  {
      file &lt;&lt; data;
      if (!file)
      {
          std::cout &lt;&lt; "Failed";
          file.clear();
      }
      file.close();
      if (file)
          std::cout &lt;&lt; "Success";
      else
          std::cout &lt;&lt; "Failed (again)";
  }
  else
      std::cout &lt;&lt; "Failed";
  
  file.clear();
  </code></pre>
  
  <p>Are they all equivalent and safe?</p>