16

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);
meneldal
  • 1,717
  • 1
  • 21
  • 30
Ishaan
  • 707
  • 1
  • 7
  • 16
  • 4
    Using an `istream` where an `ostream` is expected will result in an error, this will save you a lot of head scratching then if you were to accidentally use an `fstream` opened in input mode, which the compiler won't complain about. – user657267 May 22 '15 at 04:44

2 Answers2

27

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.

meneldal
  • 1,717
  • 1
  • 21
  • 30
1

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...
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • Would you also suggest using that file checking method over "if (input.is_open())"? – Ishaan May 22 '15 at 04:50
  • @ishyfishy: definitely - I don't remember the last time I used `is_open()`. – Tony Delroy May 22 '15 at 04:59
  • 1
    This method has a couple interesting points: The stream will only live until the end of the `if` so you don't have to worry about forgetting to close the file and you can make use of the implicit conversion to bool of the streams. – meneldal May 22 '15 at 05:00
  • Just a note that this answer generated [another question](http://stackoverflow.com/q/43215529/10077), and it seems this syntax is not quite valid. Brace initialization would work for C++11 and later, though. – Fred Larson Apr 04 '17 at 19:40
  • 2
    @FredLarson: thanks - must have been a non-Standard extension on some compiler I used before that accepted parentheses, but have found myself needing to use braces recently. Answer updated accordingly. Cheers. – Tony Delroy Apr 04 '17 at 23:31