title: How to save and also read c++ fstream file without closing it
body: <p>I opened a file both read and write mode</p>
  
  <p>using the following statement</p>
  
  <pre><code>file.open(fileName, ios::in | ios::out | ios::trunc);
  </code></pre>
  
  <p>my main purpose for opening the file in both mode is, read and write the file at the same time.</p>
  
  <p>But In my code scenario,</p>
  
  <p>when I am reading the file after writing it, the ouput showing blank that means,
  it is not saving my writing contents because I am not closing it.</p>
  
  <p>And I want to close the file after finishing both write and read the operation</p>
  
  <p>I found a solution in Stack Overflow,</p>
  
  <p>to use <strong>flush()</strong> function to save the file without closing</p>
  
  <pre><code>file.flush();
  </code></pre>
  
  <p>but, the problem is it's not working for my case</p>
  
  <p>So, how can I save c++ fstream file without closing?</p>
  
  <p>Here's my full code for better understanding</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;fstream&gt;
  using namespace std;
  
  
  int main(int argc, char const *argv[])
  {
      string fileName = "text.txt";
  
      fstream file;
  
  
      file.open(fileName, ios::in | ios::out | ios::trunc);
  
      if (file.is_open())
      {
          file &lt;&lt; "I am a Programmer" &lt;&lt; endl;
          file &lt;&lt; "I love to play" &lt;&lt; endl;
          file &lt;&lt; "I love to work game and software development" &lt;&lt; endl;
          file &lt;&lt; "My id is: " &lt;&lt; 1510176113 &lt;&lt; endl;
  
          file.flush(); // not working 
      }
      else
      {
          cout &lt;&lt; "can not open the file: " &lt;&lt; fileName &lt;&lt; endl;
      }
  
      if (file.is_open())
      {
          string line;
  
          while(file)
          {
              getline(file, line);
  
              cout &lt;&lt; line &lt;&lt; endl;
          }
      }
      else
      {
          cout &lt;&lt; "can not read file: " &lt;&lt; fileName &lt;&lt; endl;
      }
  
      file.close();
  
      return 0;
  }
  </code></pre>