proper use of ifstream and ofstream

Hi, I have a file which is used as database for user ID. My program look into it to see which is the last used ID and increment it by one before writing it again into the same file. So I basically need to open it in read and write. The problem is that for what I can seen when I open it in write mode it gets deleted. So I have arranged something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
        ifstream dbin("id.db");

        while (true) {
                dbin >> id;
                if( dbin.eof() ) break;
        }

        // close id.db now so that we can open it later in append
        dbin.close();
        // open it again in write mode (append)
        ofstream dbout("id.db",ios::app);

        dbout << ++id << endl;


Is this the right way I am supposed to do? Or is there something more elegant?
Here you go. Sometimes I scare myself.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream>

int main()
{
    std::fstream dbin("id.db", std::fstream::in | std::fstream::out);
    int id=0; // I suppose it's an int?

    while (dbin >> id);

    dbin.clear();
    dbin << ++id << std::endl;
    return 0;
}


Edit: std::fstream::app flag not needed.

Edit 2: for complex input files, I guess your way is the right way, though.
My code is very specific and its only improvement is that it doesn't open the file twice, which isn't that much.
Last edited on
¿Why don't just store the integer that you want, instead of the numbers from 1 to n?
Topic archived. No new replies allowed.