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;
}