http://www.makepovertyhistory.org

Archive for May, 2009

std::fstream

Posted in C++, Development on May 7th, 2009
Hmmm
std::fstream f("filename",std::ios_base::binary | std::ios_base::in | std::ios_base::out);

A version of the above code was posted on a website and the poster inquired.

Why doesn’t this just open a binary file and if it’s not there create one?

I vaguely remembered something about this instance and at first I thought it was in relation to where data would be written to. Replying I wrote that adding the “trunc” flag would create the file if needed [1] but also truncate the file as the flag would suggest. Once I  had actually  thought about it I came to the realisation this was just nonsense, but there was a reason for my madness.

Although the C++ standard does not mention anything about this, that I can find, I believe it is due to C’s fopen modes and that would make sense. Would a combination of both the out and in flags be equivalent to “r+” or “w+”? Personally I suspect that the default for this situation is “r+” and by adding the truncate flag it becomes “w+”.

Yet I wonder if this is reliable across all platforms?

[1] If you have the correct privalages and the location is not on a read only disc etc.