write a small b before capital B in the file. This isn't easy.

Suppose my file a.txt has "ABC" written in it. Now I want to write a small b before capital B in the file. How will I do it. I've tried to do it but i'm having problems.
1. When opened in app mode seekp doesn't work.
2. When opened normally previous written data is erased.
Then rewrite the whole thing again.
I mean,
-copy the content into your programme
-add b before B, maybe using std::string::find();
-write the editted stuff back to file.

Aceix.
You can only overwrite existing content in files or add more to the end of the file. If you want to insert in the middle, you have to rewrite everything after that point. The easiest way is as Aceix recommended: read it completely into a string, deal with the string, then write the string back to the file, overwriting the old contents.
Thanks Aceix and L B.
This is how I would do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <fstream>
#include <cstdio>

int main()
{
    const char* const file_name = "a.txt" ;
    const char* const modified_file_name = "a.modified.txt" ;

    {
        std::ifstream in(file_name) ;
        std::ofstream out(modified_file_name) ;
        in >> std::noskipws ;
        char c ;
        while( in >> c )
            if( c == 'B' ) out << "bB" ;
            else out << c ;
    }

    /* if there were no errors */
         if( std::remove(file_name) == 0 )
            std::rename( modified_file_name, file_name ) ;
}
Thanks a lot JLBorges!
Topic archived. No new replies allowed.