What is the difference among ios::app, out, and trunc in c++?

ios::out is the default mode for std::ofstream, it means that output operations can be used (i.e. you can write to the file).

ios::app (short for append) means that instead of overwriting the file from the beginning, all output operations are done at the end of the file. This is only meaningful if the file is also open for output.

ios::trunc (short for truncate) means that when the file is opened, the old contents are immediately removed. Again, this is only meaningful if the file is also open for output.

Your code just uses the default ios::out mode. So it starts writing from the beginning of the file, but doesn’t remove the old contents. So the new contents will overlay what’s already there — if the file is originally 10 bytes long, and you write 3 bytes, the result will be the 3 bytes you write followed by the remaining 7 bytes of the original contents. More concretely, if the file originally contains:

Firstname Lastname
30

and you write FN LN and then 20 (with newlines after each), the resulting file will look like:

FN LN
20
 Lastname
30

because you only overwrite the first 9 bytes of the file (assuming Unix-style newlines).

Once you’ve opened the file, all outputs to the file are written sequentially after each other, unless you use outfile.seekp() to go to a different location. It doesn’t go back to the beginning of the file for each thing you write. seekp() has no effect if the ios::app is used; then every write goes at the end of the file.

Leave a Comment