27

What the point of the std::ios_base::ate (other than std::ios_base::app, for example) and std::ios_base::trunc (other than std::ios_base::out, for example)?

And should i preferly write std::ios_base::smth instead of std::ios::smth?

Jaffa
  • 12,442
  • 4
  • 49
  • 101
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

1 Answers1

24

std::ios_base::ate position the cursor at the end of the text whereas std::ios_base_app appends text (with a write operation) at the end, though you can still read from the beginning :)

std::ios_base::trunc truncates the file so it is emptied, whereas std::ios_base::out just specify you want to write to the stream.

I currently can't quote the standard (on my tablet and Acrobat Reader won't let met copy) but from paragraph 27.4.2.1.4 from ISO 14882:1998 the information you can see on the link is almost exact: http://cplusplus.com/reference/iostream/ios_base/openmode/

To sum up:

std::ios_base::app = append

Append at the end of the stream by "seek[ing] to end before each write"

std::ios_base::ate = At The End

Open and seek immediately at the end after opening

std::ios_base::binary = binary

Perform operation in binary as opposed to text

std::ios_base::in = input

Open in read mode

std::ios_base::out = output

Open in write mode

std::ios_base::trunc = truncate

Truncate the stream on opening.

These values are just flags, so you can open a stream in read/write binary at the end with :

std::ios_base::in | std::ios_base::out | std::ios_base::ate | std::ios_base::binary

Concerning the way of using those values, it is as you wish. They are declared as public static fields in std::ios_base class (see 27.4.2) thus it is possible to access them using std::ios::ate or even something like cout.binary !


The points where you must take attention is that std::ios_base::ate does NOT imply std::ios_base::app nor does std::ios_base::out implies std::ios_base::trunc. Each field has a different meaning, and a different case of use, though most of them can't be used alone :)

Jaffa
  • 12,442
  • 4
  • 49
  • 101
  • But std::ios_base::out also clear the data in the file, no? Can you give me an example where std::ios_base::out don't clear the file? – FrozenHeart Sep 03 '12 at 19:47
  • From here : http://cplusplus.com/reference/iostream/ios_base/openmode/ you get the definition of each value. Moreover, this answer @veer's comment about std::ios_base::in and std::ios::in – Jaffa Sep 03 '12 at 19:49
  • And what do you mean by "you can still read from the beginning"? Can you give me an example, please? – FrozenHeart Sep 03 '12 at 19:51
  • I mean that ios::ate positions the cursor at the end of the stream, so you can still move it around if you like (and if the stream isn't empty and permit it) – Jaffa Sep 03 '12 at 19:53
  • Why i can't do this with std::ios_base::app? I can use seekp also – FrozenHeart Sep 03 '12 at 19:59
  • std::ios_base::app seek to the end before each write operation – Jaffa Sep 03 '12 at 20:05