Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ - fstream and ofstream

What is the difference between:

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

and

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

Are their function the same?

like image 312
Robin Avatar asked Apr 24 '14 02:04

Robin


People also ask

What is the difference between ofstream and fstream?

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.

Should I use fstream or ifstream?

ofstream is output file stream which allows you to write contents to a file. fstream allows both reading from and writing to files by default. However, you can have an fstream behave like an ifstream or ofstream by passing in the ios::open_mode flag.

What is fstream in C?

ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file. ofstream is an output file stream. It is a special kind of ostream that writes data out to a data file.

Can we use C file handling in C++?

Even though most C++ compilers do not have different linkage for C and C++ data objects, you should declare C data objects to have C linkage in C++ code. With the exception of the pointer-to-function type, types do not have C or C++ linkage.


2 Answers

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.

like image 174
user657267 Avatar answered Sep 21 '22 08:09

user657267


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.

like image 21
Danqi Wang Avatar answered Sep 22 '22 08:09

Danqi Wang