4

While searching for file reading examples in C++, I notice that many examples use

  • std::ios::binary vs std::ifstream::binary
  • std::ios::beg vs your_file_stream.beg
  • std::ios::end vs your_file_stream.end

Are there any differences in these examples, and if not, why are they both included in the STL?

João Pires
  • 927
  • 1
  • 5
  • 16
  • While a good question, i think this is primarily opinion based. They are the same thing, just different ways to reference them. – Fantastic Mr Fox Jan 11 '17 at 17:14
  • My feeling is the first part is opinion based, but the second one isn't. – Bathsheba Jan 11 '17 at 17:23
  • I think you may have a typo in your question. Are you really asking if `std::ios::beg` is the same as `std::ios::end`? Are you really asking if the beginning of something is the same as the end of something? – Robᵩ Jan 11 '17 at 17:45
  • The guy who edited my question didn't edit it well, I'll correct ;) – João Pires Jan 11 '17 at 17:46
  • Yeah, that was a bad edit. Not just bad formatting, but he also fundamentally changed your question in the final paragraph. – Robᵩ Jan 11 '17 at 17:48
  • @DagobertoPires - I'm that guy, sorry. I didn't look at the examples well enough I'm afraid. However, the original question was way too opinion-based. – owacoder Jan 11 '17 at 17:49

2 Answers2

3

std::ios::binary vs. std::ifstream::binary is largely down to personal choice, but I always use the more "fundamental" definition insofar that it's further up the inheritance tree if you get my meaning. Hence std::ios::binary is my choice.

As for std::ios::beg and your_file_stream.beg, I'd plump for the former: it's pointless and obfuscating to reach a static member via an instance.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

They ARE the same, since ifstream inherit from ios...

There is no "idiom" there. Just opinions.

My personal one is that you shold protect you code in a way a change in the library it uses will retain you code consistency.

So your_file_stream.end is always coherent to your_file_stream whatever it is and however it is composed in present and future versions. And even if it happens to be different respect to other stream types, will always work.

If you don't have an instance, std::ifstream::binary is always coherent with ifstream, however it will be composed now and in the future. And will word even if it will be different from other types.

If you're writing a polymorphic runtime-function taking std::ios&, than std::ios::binary is fine.

However it will be unlikely those things will ever be changed, so ... it does not really matters.

Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63