c++ - fstream and ofstream

后端 未结 2 617
耶瑟儿~
耶瑟儿~ 2021-01-11 16:30

What is the difference between:

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

and

ofstream textfile;
textfile.open(\"Test.t         


        
2条回答
  •  粉色の甜心
    2021-01-11 17:22

    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.

提交回复
热议问题