View Single Post
Old 05-12-2005, 04:44 AM   #3 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Code like...
Code:
file.seekp(file.tellg() - sizeof(char));
...is not advisable, since the standard never guarantees proper conversion.
Also, after a read we want to reposition the write pointer. And after a write, we want to reposition the put pointer. Otherwise we end up with undefined behaviour.
Also...
Code:
while(file.eof()==0)
... we don't want to use eof() to decide whether file i/o should stop.
In general here is the code with comments:
Code:
#include <iostream>
#include <fstream>
#include <ios>

int main()
{
  //1) Open file in binary for more accurate positioning.
  //2) std::ios_base::ate is not needed.
  std::fstream file( "m.txt", std::ios_base::in |
    std::ios_base::out | std::ios_base::binary );
  //I initialize ch as well, just a neat thing to do.
  char ch( 0 );
  //Stream reader returns a value: acts like "false" if stream not good.
  while( file.get( ch ) )
  {
    if( 'c' == ch )
    {
      file.putback( ch );
      //Reposition put pointer after a read.
      file.tellp();
      file.put( '*' );
      //reposition get pointer after a write.
      file.tellg();
    }
  }
  return 0;
}
__________________
Valmont is offline   Reply With Quote