问题描述
我遇到了一个奇怪的行为,最不奇怪的对我。这是我的程序,我使用Visual Studio 2010速成版。
I've come across an odd behavior of the ofstream, 'least odd to me. Here's my program, i'm using 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;
}
这将产生正确的输出。
现在如果我用下面的代码替换第9行, p>
Now if i replace the 9th line with the following code,
file.open("file.txt", std::ios::ate);
我得到此输出。
但如果我再次替换第9行,这次使用此代码,
But if i replace the 9th line again, this time with this code,
file.open("file.txt", std::ios::ate | std::ios::in );
我得到这个输出。
现在,我想问题是,有人能帮我做出任何意义吗?为什么最后一个解决方案工作,但中间的不工作。
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:更正了主要功能。
推荐答案
一个 ofstream
默认为 std :: ios :: trunc
- 截断现有内容的标志。传递 std :: ios :: in
禁用截断(除非还指定了 trunc
标志)。
An ofstream
defaults to std::ios::trunc
-- the flag to truncate the existing content. Passing std::ios::in
disables truncation (unless the trunc
flag is also specified).
实际上,规则是如果 trunc
标志, fstream
执行截断,或者如果使用 out
标志,在
和 app
(通知应用程式
与 ate
,应用程式
repositions 每个写入,而 ate
只影响初始指针)。 ofstream
自动设置 out
。 trunc
不能使用 out
。
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). ofstream
automatically sets out
. trunc
cannot be used without out
.
这篇关于的流行奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!