18

What is the difference between:

fstream texfile; textfile.open("Test.txt"); 

and

ofstream textfile; textfile.open("Test.txt"); 

Are their function the same?

2 Answers 2

16

ofstream only has methods for outputting, so for instance if you tried textfile >> whatever it would not compile. fstream can be used for input and output, although what will work depends on the flags you pass to the constructor / open.

std::string s; std::ofstream ostream("file"); std::fstream stream("file", stream.out); ostream >> s; // compiler error stream >> s; // no compiler error, but operation will fail. 

The comments have some more great points.

Sign up to request clarification or add additional context in comments.

2 Comments

Also, ofstream::open defaults to openmode ios_base::out, and fstream::open defaults to ios_base::in | ios_base::out
Moreover, in the case of std::fstream, attempting to open the file will fail if the file does not exist. This is in contrast to std::ofstream which creates a file if one cannot be found. One would have to add the std::ios_base::trunc flag to the mask when calling the constructor or open() on an std::fstream.
3

Take a look at their pages on cplusplus.com here and here.

ofstream inherits from ostream. fstream inherits from iostream, which inherits from both istream and stream. Generally ofstream only supports output operations (i.e. textfile << "hello"), while fstream supports both output and input operations but depending on the flags given when opening the file. In your example, the open mode is ios_base::in | ios_base::out by default. The default open mode of ofstream is ios_base::out. Moreover, ios_base::out is always set for ofstream objects (even if explicitly not set in argument mode).

Use ofstream when textfile is for output only, ifstream for input only, fstream for both input and output. This makes your intention more obvious.

3 Comments

y ! cite cppreference.com instead
@Cheersandhth.-Alf cppreference.com is prettier, but google returns me cplusplus.com for c++ fstream. What are other advantages of cppreference.com over cplusplus.com?
@DanqiWang: generally more correct due to better peer-review

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.