c++ - fstream and ofstream

Robin picture Robin · Apr 24, 2014 · Viewed 23k times · Source

What is the difference between:

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

and

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

Are their function the same?

Answer

user657267 picture user657267 · Apr 24, 2014

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.