title: Change a text file in random access
body: <p>I have a text file and want to change it in some places, for example in byte range 4030 to 4060, in this way:</p>
  
  <ul>
  <li>if there is a character 'C' or 'c' followed by 'G' or 'g' ,must be changed in 'B' character</li>
  </ul>
  
  <p>The input file is a text file and I want to get a changed text output file.  There is no random access in text file and so I must open file in binary form and make changes, but the output file will be binary and I don't have any idea to get a text output. The code is below:    </p>
  
  <pre><code>int main()
  {
      string str, cstr;
      ReadTextFile("in", 4030, 4060);
      return 0;
  }
  
  string ReadTextFile(string path, int from, int to)
  {
      fstream fp(path.c_str(), ios::in|ios::out|ios::binary);
      char *target;
      string res, str;
      target = new char[to - from + 1];
      if (!target)
      {
          cout &lt;&lt; "Cannot allocate memory." &lt;&lt; endl;
          return "";
      }
      fp.seekg(from);
      fp.read(target, to - from);
      target[to - from] = 0;
      res = target;
      str = changestring(res);
      fp.seekg(from);
      fp.write((char *)&amp;str, to-from);
      return res;
  }
  
  string changestring(string str)
  {
      int l = str.length();
      l = l-1;
      for (int i = 0; i &lt;= l; i++)
      {
          if (str[i] == 'C' ||  str[i] == 'c')
          {
              int j = i+1;
              if (str[j] == 'G' || str[j] == 'g')
                  str[i] = 'B';
          }
      }
      return str;
  }
  </code></pre>