ofstream open?

Hi, I am learning about the streams and files etc. And I am on the ofstream open, and my book says that the prototype for the open for the ofstream is

  void ofstream::open(const char *filename, ios::openmode mode = ios::out | ios::trunc);

but I didnt understand why all output streams would truncate so when i looked it up online, I found the code below, which doesnt mention trunc, so I am wondering. is trunc set normally or is my book wrong?

void open (const char* filename,  ios_base::openmode mode = ios_base::out);
Check the reference; https://en.cppreference.com/w/cpp/io/basic_ofstream/open

Looks like your book is wrong. Maybe it's very old. There was a time when C++ was much less well-defined.
By definition, ofstream truncates the file when opened.

See https://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream See point 2)
See https://en.cppreference.com/w/cpp/io/basic_filebuf/open

basic_filebuf::open() is called with mode "w" - which truncates.
Those snippets are showing how the "default" open mode is defined. And don't forget with modern C++ (C++11 or better) you can also use std::string, or a std::filesystem::path as the first parameter.

Things to understand about an ofstream:

1. An ofstream is always an output stream (note the "=" in those snippets).

2. By default an ofstream truncates the file when opening.

3. You need to use a different open mode to avoid the truncation (std::ios::app).

This part of the prototype is a 'default value'

ios::openmode mode = ios::out | ios::trunc

is you do not specify the 2nd argument this is used, or if you do specify the 2nd arguments the options you set are used,

for example

std::ofstream fout.open("filename.dat", std::ios::out | std::ios::app)

will open the file in append mode.
Registered users can post here. Sign in or register to post.