Help: reading and writing to the same file.

Lets say I want to take every character in a file and make it lower case. I could do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 string path = "file.txt";
    ifstream in{path};

    string result;
    while(in) {
        char ch;
        in.get(ch);
        ch = tolower(ch);
        result += ch;
    }
    in.close();

    ofstream out{path};
    if(out){
        out << result;
    }
    out.close();


This works, but I feel like there is an even better solution out there. Can anyone give me some insight?
Last edited on
Maybe use std::stringstream to read/write the file?
http://www.cplusplus.com/reference/sstream/stringstream/

To convert to lower case, maybe try this:
http://www.cplusplus.com/reference/algorithm/for_each/
I was thinking of perhaps a way to immediately change the character after the read without dealing with seekp() or anything like that. That may not even be possible though.
TinyTertle wrote:
a way to immediately change the character after the read

What do you mean by this?

1
2
3
4
5
6
7
8
9
10
11
12
    string path = "file.txt";
    ifstream in{path};

    std::stringsteam data{};
    data << in.rdbuf( );
    in.close();

    std::for_each( data.str( ).begin( ), data.str( ).end( ), tolower );

    ofstream out{path};
    out << data.str( );
    out.close();
Something more like

1
2
3
4
5
6
//...
while(in) {
     file.get(ch);
     file.somehow_convert_this_char_to_lower(ch);
}
/...

I mean that the conversion takes place as we are reading in the characters.
Last edited on
Topic archived. No new replies allowed.