C ++ - stream and stream

What's the difference between:

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

and

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

Are their functions the same?

+6
source share
2 answers

ofstream have only output methods, so if you tried textfile >> whatever , it will not compile. fstream can be used for input and output, although what works will depend on the flags you pass to the / open constructor.

 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. 

There are some more great comments in the comments.

+5
source

Take a look at your pages at cplusplus.com here and here .

ofstream inherited from ostream . fstream inherits from iostream , which inherits from both istream and stream . Typically, ofstream only supports output operations (ie. Text file <"hello"), and fstream supports both output and input operations, but depending on the flags set when the file was opened. In your example, the default open mode is ios_base::in | ios_base::out ios_base::in | ios_base::out . The open mode ofstream is ios_base::out . In addition, ios_base::out always set for object objects (even if it is not explicitly specified in argument mode).

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

0
source

All Articles