Odd behavior

I came across the strange behavior of thestream, โ€œleast strange to me. Here is my program, I am 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 gives the correct result.

something1something2

Now, if I replaced the 9th line with the following code,

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

I get this conclusion.

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 conclusion.

something1something2

Now, probably, the question is, can someone help me figure this out? Why the latter solution works, but the average does not.

EDIT: Fixed main function. You will learn something every day.

+4
source share
1 answer

An ofstream by default std::ios::trunc - flag for trimming existing content. Passing std::ios::in disables truncation (unless the trunc flag is trunc ).

Actually, the rule is that fstream truncates if the trunc flag is trunc or the out flag is used, and neither in nor app (the app notification is different from ate , app reorders each entry, and ate only affects the original pointer). ofstream automatically sets out . trunc cannot be used without out .

+7
source

Source: https://habr.com/ru/post/1415881/


All Articles