title: replace text in middle of the file
body: <p>I have <code>.txt</code> file and there are lines:</p>
  
  <pre><code>username1:123456789:etc:etc:etc:etc
  username2:1234:etc:etc:etc:etc
  username3:123456:etc:etc:etc:etc
  username4:1234567:etc:etc:etc:etc
  </code></pre>
  
  <p>username1 - username;
  123456789 - password;
  etc - more text.</p>
  
  <p>I have code to read file and find line where is <code>username</code> what I need. Also code change password, but there is problem if new password is longer that old one then it looks like:</p>
  
  <pre><code>username3:11111111111tc:etc:etc:etc
  </code></pre>
  
  <p>if new password is shorter then it looks like:</p>
  
  <pre><code>username1:111111789:etc:etc:etc:etc
  </code></pre>
  
  <p>I have length of new password, but how can I get length of old one and replace it properly?</p>
  
  <p><strong>My code</strong></p>
  
  <pre><code>include&lt;iostream&gt;
  #include&lt;fstream&gt;
  #include &lt;cstring&gt;
  
  using namespace std;
  
  int main() {
      int i=0;
      bool found = false;
      string line, username;
      char newpass[255] = "555555555555555";
      long length, plen;
  
  
      cout&lt;&lt;"Insert username: ";
      cin&gt;&gt;username;
      username+=":";
      fstream changeLINE("/.../testaDoc.txt");
  
      if (!changeLINE) {
          cout &lt;&lt; "Can't find the file or directory!" &lt;&lt; endl;
      }
      else
  
          while (getline(changeLINE, line) &amp;&amp; !found) {
              i++;
  
              if (line.find(username) != string::npos) {
                  length = changeLINE.tellg();
                  changeLINE.seekg((length - line.length()) + username.length() - 1);
                  changeLINE.write("", strlen(newpass));
                  cout &lt;&lt; line &lt;&lt; " line " &lt;&lt; i &lt;&lt; endl;
                  found = true;
              }
          }
  
      if (!found)
          cout &lt;&lt; "User with username = " &lt;&lt; username &lt;&lt; " NOT FOUND!";
  
      changeLINE.close();
  
  }
  </code></pre>
  
  <p>I'm working on Linux, writing in C++.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>Maybe there are way to add string in text, but not replace it and also way to erase string by not replacing it? Then I could read length of old password compare it with new password and delete/add letters in string to replace it properly.</p>