fstream

If fstream is for reading, writing, or both, then what is the purpose of using either ofstream or ifstream? I have searched the articles on this site that gives the definitions and my class book. Nowhere does it mention why I would use ofstream or ifstream instead of fstream. Any information will be appreciated. Thank you in advance.

ifstream is an fstream with the mode set to input. If the file does not exist, the stream is in a fail state.

ofstream is an fstream with the mode set to output and truncate (file is created if it not exist and contents erased if it does exist).

You can't write to an ifstream and you can't read from an ofstream. Depending upon the mode specified when an fstream file was opened, both can be done.
Thank you.
why I would use ofstream or ifstream instead of fstream.
To express intent. If I see an ofstream object, I immediately see that it's a output stream, used to write a file, and that's all it can ever be. If I see an fstream object, it's ambiguous, and requires more time to for me to actually understand the purpose of the object.
Last edited on
Topic archived. No new replies allowed.