mardi 23 janvier 2018

tellp() returns -1 after seekp() in ate mode

I was looking at seekp and tellp() functionality. In below code, tellp() returns -1 after f2.seekp(10). I could not understand why -1 is returned. This I tested in both compilers (Visual Studio as well as TDM GCC 4.9.2 64 bit) and results are consistent. There is also another post similar to this here and in that case issue seems to be with the compiler and visual studio returns correct results. I raised separate post because issues are different.

/** Open in ate mode. ios::in is used to ensure that file is not destroyed. */
    ofstream f2("h2.txt", ios::ate | ios::out | ios::in);
    if (!f2)   //0 means error. You can also use f1.fail()
    {
        // open failed
        cerr << "cannot open the file\n";
        exit(-1);
    }
    ios::pos_type currentPos = f2.tellp();
    cout << "Initial Write Pointer Position = " << currentPos << endl;
    // Write some data. It should be written at the end.
    f2 << 20;
    currentPos = f2.tellp();
    cout << "Write Pointer Position after write = " << currentPos << endl;

    // Seek to specific position. File pointer must change accordingly.
    f2.seekp(10);
    currentPos = f1.tellp();
    cout << "Write Pointer Position after seek = " << currentPos << endl;

    // Write some data
    f2 << "ABC";
    currentPos = f2.tellp();
    cout << "Final Write Pointer seek and write = " << currentPos << endl;
    f2.close();

Aucun commentaire:

Enregistrer un commentaire