c++ - ofstream 开放模式 : ate vs app

标签 c++ visual-studio-2012 fstream

This问题询问 appate 之间的区别以及答案和 cppreference暗示唯一的区别是 app 意味着写光标在每次写操作之前放在文件的末尾,而 ate 意味着写光标放在仅在打开时文件末尾。

我实际看到的(在 VS 2012 中)是指定 ate 丢弃现有文件的内容,而 app 会不是(它将新内容附加到以前存在的内容)。换句话说,ate 似乎暗示了 trunc

以下语句将“Hello”附加到现有文件:

ofstream("trace.log", ios_base::out|ios_base::app) << "Hello\n";

但是下面的语句只用“Hello”替换了文件的内容:

ofstream("trace.log", ios_base::out|ios_base::ate) << "Hello\n";

VS 6.0 的 MSDN 文档暗示这不应该发生(但这句话似乎已在 Visual Studio 的更高版本中撤回):

ios::trunc: If the file already exists, its contents are discarded. This mode is implied if ios::out is specified, and ios::ate, ios::app, and ios:in are not specified.

最佳答案

您需要将 std::ios::instd::ios::ate 组合,然后查找文件末尾并附加文本:

假设我有一个文件“data.txt”,其中包含这一行:

"Hello there how are you today? Ok fine thanx. you?"

现在我打开它:

1: std::ios::app:

std::ofstream out("data.txt", std::ios::app);

out.seekp(10); // I want to move the write pointer to position 10

out << "This line will be appended to the end of the file";

out.close();

结果不是我想要的:没有移动写指针,但只有文本始终附加到末尾。

2: std::ios::ate:

std::ofstream out2("data.txt", std::ios::ate);

out2 << "This line will be ate to the end of the file";

out2.close();

上面的结果不是我想要的,没有附加文本,但内容被截断了!

要解决这个问题,请结合使用 atein:

std::ofstream out2("data.txt", std::ios::ate | std::ios::in);

out2 << "This line will be ate to the end of the file";

out2.close();

现在文本附加到末尾,但有什么区别:

正如我所说,应用程序不允许移动写入指针,但 ate 可以。

std::ofstream out2("data.txt", std::ios::ate | std::ios::in);

out2.seekp(5, std::ios::end); // add the content after the end with 5 positions.

out2 << "This line will be ate to the end of the file";

out2.close();

上面我们可以将写指针移动到我们想要的位置,而在应用程序中我们不能。

关于c++ - ofstream 开放模式 : ate vs app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47014463/

相关文章:

visual-studio-2012 - 如何在 Visual Studio 2012 中包含 TypeScript 文件并编译整个文件?

c++ - 程序不会编译

c++ - 静态数组声明

visual-studio - 是否可以将自定义资源类型添加到 .NET .resx 文件?

c++ - 为什么要在定义宏之前取消定义它们?

嵌套结构的 C 问题(看起来 1 个实例是在没有明确定义的情况下定义的)

c++ - 编译错误:ifstream::open 只接受引号 ""中的字符串值而不接受字符串变量

c++ - 文件 I/O 操作 - 奇怪的字符输入?

c++ - 使用类指针与实例

c++ - ifstream.open() 不打开文件