简体   繁体   English

流奇怪的行为

[英]ofstream odd behavior

I've come across an odd behavior of the ofstream, 'least odd to me. 我遇到过ofstream的奇怪行为,对我来说最不奇怪。 Here's my program, i'm using Visual Studio 2010 Express Edition. 这是我的程序,我使用的是Visual Studio 2010 Express Edition。

int main () {

    std::ofstream file("file.txt");
    file << "something1";
    file.close();

    file.open("file.txt", std::ios::ate | std::ios::in );
    file << "something2";
    file.close();

    return 0;
}

This produces the correct output. 这会产生正确的输出。

something1something2 something1something2

Now if i replace the 9th line with the following code, 现在,如果我用以下代码替换第9行,

file.open("file.txt", std::ios::ate);

i get this output. 我得到这个输出。

something2 something2

But if i replace the 9th line again, this time with this code, 但是,如果我再次替换第9行,这次使用此代码,

file.open("file.txt", std::ios::ate | std::ios::in );

i get this output. 我得到这个输出。

something1something2 something1something2

Now, i guess the question is, could somebody help me out make any sense out of this? 现在,我想问题是,有人可以帮我解决这个问题吗? Why does the last solution work, but the middle one doesn't. 为什么最后一个解决方案有效,但中间解决方案没有。

EDIT: Corrected the main function. 编辑:纠正了主要功能。 You learn something every day. 你每天都学到一些东西。

An ofstream defaults to std::ios::trunc -- the flag to truncate the existing content. ofstream默认为std::ios::trunc - 用于截断现有内容的标志。 Passing std::ios::in disables truncation (unless the trunc flag is also specified). 传递std::ios::in会禁用截断(除非还指定了trunc标志)。

Actually, the rule is that fstream performs truncation if the trunc flag is used, or if the out flag is used and neither in nor app (notice app is different from ate , app repositions every write, while ate only affects the initial pointer). 实际上,规则是如果使用了trunc标志, fstream会执行截断,或者如果使用out标志,并且既没有in也没有app (注意appate不同, app重新定位每次写入,而ate只会影响初始指针)。 ofstream automatically sets out . ofstream自动out trunc cannot be used without out . trunc不能没有被使用out

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM