代码之家  ›  专栏  ›  技术社区  ›  Patrik Valkovič

ios::ate不会移动到文件末尾

  •  1
  • Patrik Valkovič  · 技术社区  · 7 年前

    我有一个小程序。

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
        fstream f("file.txt", ios::out);
        f << "Hello world!" << endl;
        f.close();
    
        fstream atEnd("file.txt", ios::out | ios::ate);
        cout << "Position: " << atEnd.tellp() << endl;
        atEnd << "You too" << endl;
        atEnd.close();
    
        return 0;
    }
    

    它应该打开文件,向其中写入一些内容,然后关闭它,并在最后再次打开,因此文本“You too”应该附加在文件的末尾。但位置始终为0,内容被重写: https://www.onlinegdb.com/online_c++_compiler ios::ate 应该 打开后立即搜索到流的末端 .

    1 回复  |  直到 7 年前
        1
  •  0
  •   JCrypter    7 年前

    我认为append模式足以满足您的需要: fstream f.open("file.txt", ios::app );

    或者,您也可以在编写之前使用seekp,尽管它不是首选。