Possible Duplicates:
Is std::ifstream significantly slower than FILE?
Which I/O library do you use in your C++ code?
I was wondering what are the pros or cons of using fstream over FILE in C++?
The one pro I think is that FILE is more efficient than fstream.
fstream is a better encapsulation and has higher level concepts. fstream is exception safe. fstream is also a stream and can be treated generically as a stream.
Usually, every mode that entails writing to the file is meant to create a new file if the given filename does not exist. Thus, we need to call the open built-in function of std::fstream to create a new file with the name provided as the first string argument.
Ifstream: File handling class that signifies the input file stream and is used for reading data from the file. Fstream: File handling class that has the ability to handle both ifstream and ofstream. It can be used to read from and write to a file.
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.
One is C and one is C++. Tomato, tomato. (That expression doesn't work nearly as well when you write it out.) My guess is that you are not likely to see a performance difference.
A very C++ inclined, anti-C person will probably tell you something along the lines of fstream
being able to deal with differing types with more ease. With FILE
you have two options -- deal in bytes or deal in format strings. Since printf
or fwrite
et al. don't know what the "real" type of their arguments are this makes it easier to screw up. There's also the fact that a C++ class will have a destructor and so you get cleanup "for free" when the object goes out of scope. (Although... Do you really want something like fflush
to silently happen in a destructor? Probably not.) To these sorts of arguments I would say that it's not really that much of a burden to use FILE
, but hey, some people feel more strongly than I on these matters.
Eventually it will boil down to what exactly your application is trying to do, and it may be that FILE
, fstream
, or both can adequately suit your needs.
Pick what works, be flexible with what other people choose, understand the arguments and don't get too religious about it. That's my advice. :-)
Imagine:
void read(istream& istr)
We could pass in an ifstream, a istrstream, or even cin. This is very useful for unit testing.
std::fstream
is typesafe, has internationalization support and is (warning: opinion) easier to use.
When a std::fstream
goes out of scope it is destructed for you, regardless of whether you forgot to fstream::close()
it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With