【问题标题】:ios::ate does not move into end of the fileios::ate 没有移动到文件末尾
【发布时间】:2018-10-07 16:04:31
【问题描述】:

我有这个小程序。

#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 应该在打开后立即搜索到流的末尾

【问题讨论】:

  • 考虑为此目的使用 ios_base::app (append) 标志,而不是 ios::ate

标签: c++ stream


【解决方案1】:

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

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

【讨论】:

  • 但是使用ios::app 我无法在文件中查找。似乎ios::out 总是截断文件,因为当我使用ios::out | ios::in | ios::ate 时它工作正常。但是,如果我想打开文件进行写入而我没有读取权限怎么办?
  • 我想我可能以错误的方式传达了它。 seekp 仅在您以 out 或 ate 模式打开文件时。使用应用程序模式,您可以避免所有这些事情。另外我认为如果你有写权限,你也有读权限。
  • 如果您更喜欢仅使用 ate 模式,请将其与 in 结合使用以进行写入,因为 out 会截断它,即 ios::ate | ios::in
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 2011-09-10
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多