问题
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;
}
This produces the correct output.
something1something2
Now if i replace the 9th line with the following code,
file.open("file.txt", std::ios::ate);
i get this output.
something2
But if i replace the 9th line again, this time with this code,
file.open("file.txt", std::ios::ate | std::ios::in );
i get this output.
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.
回答1:
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).
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.
来源:https://stackoverflow.com/questions/10875134/ofstream-odd-behavior