Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifstream and ofstream or fstream using in and out

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);
like image 272
Ishaan Avatar asked May 22 '15 04:05

Ishaan


People also ask

Should I use fstream or ifstream?

It is basically possible to never use ifstream and ofstream and always use fstream with the required flags. But it is prone to accidental errors while setting the flags. Hence, using ifstream you can be sure that writes will never occur and with ofstream only writes will take place.

What is ifstream and ofstream 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.


2 Answers

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.

like image 83
meneldal Avatar answered Oct 03 '22 19:10

meneldal


Just use the more concise form unless you need different behaviour... to do otherwise is just to create room for more errors. FWIW, when possible I prefer to scope the stream and check the open worked like this:

if (std::ifstream input{"input_file.txt"})
    ...use input...
else
    ...log and/or throw...
like image 43
Tony Delroy Avatar answered Oct 03 '22 21:10

Tony Delroy