dre*_*eta 4 c++ file-io iostream
我遇到过ofstream的奇怪行为,对我来说最不奇怪.这是我的程序,我使用的是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;
}
Run Code Online (Sandbox Code Playgroud)
这会产生正确的输出.
something1something2
现在,如果我用以下代码替换第9行,
file.open("file.txt", std::ios::ate);
Run Code Online (Sandbox Code Playgroud)
我得到这个输出.
something2
但是,如果我再次替换第9行,这次使用此代码,
file.open("file.txt", std::ios::ate | std::ios::in );
Run Code Online (Sandbox Code Playgroud)
我得到这个输出.
something1something2
现在,我想问题是,有人可以帮我解决这个问题吗?为什么最后一个解决方案有效,但中间解决方案没有.
编辑:纠正了主要功能.你每天都学到一些东西.
一个ofstream默认为std::ios::trunc-旗截断现有内容.传递std::ios::in禁用截断(除非trunc还指定了标志).
实际上,规则是fstream在使用trunc标志时执行截断,或者如果使用out标志,in也不使用标志app(通知app不同ate,app重新定位每次写入,而ate只影响初始指针). ofstream自动设定out. trunc不能没用out.
| 归档时间: |
|
| 查看次数: |
544 次 |
| 最近记录: |