首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >开放模式: ate与app

开放模式: ate与app
EN

Stack Overflow用户
提问于 2017-10-30 11:45:02
回答 1查看 8.8K关注 0票数 7

问题询问了appate之间的区别,答案和优先选择都意味着唯一的区别是app意味着在每次写入操作之前将写入游标放在文件的末尾,而ate则意味着只在打开时才将写入游标放在文件的末尾。

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

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

代码语言:javascript
复制
ofstream("trace.log", ios_base::out|ios_base::app) << "Hello\n";

但是下面的语句将文件的内容替换为"Hello":

代码语言:javascript
复制
ofstream("trace.log", ios_base::out|ios_base::ate) << "Hello\n";

VS 6.0的MSDN文档意味着不应该发生这种情况(但这句话似乎在以后版本的Visual中被撤回了):

ios::trunc:如果文件已经存在,则其内容将被丢弃。如果指定了ios::out,而未指定ios::ate、ios::app和ios:in,则暗示此模式。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-30 12:17:49

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

假设我有一个文件"data.txt“,其中包含以下行:

代码语言:javascript
复制
"Hello there how are you today? Ok fine thanx. you?"

现在我打开它:

1: std::ios::app:

代码语言:javascript
复制
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:

代码语言:javascript
复制
std::ofstream out2("data.txt", std::ios::ate);

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

out2.close();

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

解决atein相结合的问题

代码语言:javascript
复制
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允许移动。

代码语言:javascript
复制
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();

在上面,我们可以移动写指针到我们想要的位置,而对于app,我们不能。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47014463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档