understanding file processing

Hi,

I have a problem understanding the way file processing works. I want to open a file, then replace all letters 'x' with 'y'. Here is an example:

1
2
3
4
5
6
7
8
9
fstream file;
file.open( "test.txt", ios::in | ios::out );
char c;
while( file ) {
  file.get( c );
  if( c == 'x' )
    file.put( 'y' );
}
file.close();

And it doesn't work...

Second simple question. For example, I get 5 letters from the file (from the middle) with get function and for example change second letter to 'g' and then want to replace the old 5 letters that I picked with the changed 5:

1
2
3
4
5
fstream file;
file.open( "test.txt", ios::in | ios::out );
char s[6];
file.get( s, 6 );
s[1] = 'g';


How to put them back to replace the old 5 letters?

Shall I use << and >> ? I want to use C-strings not strings.

Is there any bad interaction between put and <<, any flush or something needed?

Sorry for my bad English and thanks in advance for help.

Peter
For your first question, you would need to back up the file pointer to the 'x' character before writing 'y', so that 'y' overwrites 'x'.

Look at seekg() and tellg() member functions.

For your second question, you need to do the same essentially.
Picture the file as a long single queue of characters with a pointer moving from start to beginning. Every time you read a character from the file, the pointer moves forward one step. Both get() and put() move the pointer forward one(or more) step(s). So as jsmith you need to move the pointer backwards to rewrite in the location as you read.
Topic archived. No new replies allowed.