ifstream and ofstream or fstream using in and out

Ishaan picture Ishaan · May 22, 2015 · Viewed 18.2k times · Source

When dealing with files, which of the two examples below is preferred? Does one provide better performance than the other? Is there any difference at all?

ifstream input("input_file.txt");
ofstream output("output_file.txt");

vs

fstream input("input_file.txt",istream::in);
fstream output("output_file.txt",ostream::out);

Answer

meneldal picture meneldal · May 22, 2015

Performance-wise, there are probably only negligible differences in this case. At best you're saving a little memory.

What matters is that the first case helps with the semantics: a std::fstream could be opened in input, output or both. Because of this you need to check the declaration to be sure while using std::ifstream and std::ofstream will make it clear what you're doing. The second case has more room for human error which is why it should be avoided.

My own rule of thumb is to use a std::fstream when you need both read and write access to the file and only in this case.