title: Issues with writing to a file in c++
body: <p>As part of parsing a file, my task involves stripping off all the comments in the file and then parsing the file. Once the parsing is completed, I need to insert the comments back at the same lines.</p>
  
  <p>To strip of comments, I read the file and check if a comment has occured and then enter a newline there.  I use Ragel to do this, and the logic works fine.</p>
  
  <pre><code>example: file.cpp 
  
    #1 /** comments */
    #2 /** comments */
    #3 
    #4 ABCD : XYZ, 123
    #5 EFGH : ABC, 987
  
  intermediate_file.cpp
   #1 
   #2 
   #3 
   #4 ABCD : XYZ, 123
   #5 EFGH : ABC, 987
  </code></pre>
  
  <p>The comments are stored with the line numbers in a <code>std::map&lt;int,string&gt;</code> , which is used later to iterate and output the string to the file, <code>intermediate_file.cpp</code>. I am using the below code for the same:</p>
  
  <pre><code>fstream m_fstr; //class member
  std::map&lt;int,std::string&gt; m_Comments_map; //to hold the comments
  
  void WriteBackCommentsToFile(void) {
    m_fstr.open("intermediate_file.cpp", ios_base::out);
    int LineNbr = 0;
    for(std::map&lt;int,std::string&gt;::iterator it = m_Comments_map.begin(); it != m_Comments_map.end(); ++it)    {
        LineNbr = it-&gt;first;
        if(m_fstr.is_open()) {
          m_fstr.seekg(std::ios::beg);
          GotoLine(m_fstr,LineNbr );
          m_fstr &lt;&lt; it-&gt;second &lt;&lt; endl;
        }
    }
  }
  
  std::fstream&amp; GotoLine(std::fstream&amp; file, unsigned int num){
      for(int i=0; i &lt; num - 1; ++i){
          file.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),'\n');
          //getline(m_fstr,ReadLine); -- another try
      }
      return file;
  }
  </code></pre>
  
  <p>After the parsing is complete, I am trying to write back the comments from the <code>m_Comments_map</code> to the file <code>intermediate_file.cpp</code>
  With the above logic, I am able to print only the first line in the file - <code>/** comments */</code> .  The rest of the contents are not written back to the file.</p>
  
  <p>I have tried printing out the contents of the <code>std::map</code> to console and verified that the comments are stored properly in the <code>std::map</code>.  The problem lies in printing out the <code>std::map</code> contents to the file. Can anyone tell me which part of my code is incorrect.?</p>
  
  <p>I have implemented the above using the logic described here : 
  <a href="https://stackoverflow.com/questions/5207550/in-c-is-there-a-way-to-go-to-a-specific-line-in-a-text-file">In C++ is there a way to go to a specific line in a text file?</a></p>