在ate模式下的seekp()之后的tellp()

时间:2018-01-23 14:15:04

标签: c++11 file-handling

我在查看seekp和tellp()功能。在下面的代码中,tellp()在f2.seekp(10)之后返回-1。我无法理解为什么返回-1。我在两个编译器(Visual Studio以及TDM GCC 4.9.2 64位)中进行了测试,结果是一致的。还有一个类似于这个here的帖子,在这种情况下问题似乎与编译器和visual studio返回正确的结果。我提出了不同的帖子,因为问题不同。

        multiDexEnabled true

编辑: 这是完整的代码。代码中存在错误,这就是结果不正确的原因。在吃模式下,seekp()没有问题。

/** 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();

0 个答案:

没有答案