【问题标题】:ofstream open modes: ate vs appofstream 开放模式:ate vs app
【发布时间】:2018-04-11 09:16:09
【问题描述】:

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:如果文件已经存在,则丢弃其内容。 如果指定了 ios::out 并且 ios::ate、ios::app、 和 ios:in 未指定。

【问题讨论】:

    标签: c++ visual-studio-2012 fstream


    【解决方案1】:

    您需要将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();
    

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

    正如我所说,app 不允许移动写指针,但 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();
    

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

    【讨论】:

    • 是的。但正如您所见,将读取标志 std::ios::in 与写入流的写入标志结合起来在 fstream 中是一种愚蠢的逻辑。
    猜你喜欢
    • 2015-05-14
    • 2020-11-03
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多