The only reason to use stdio (i.e. the FILE*
family of functions) in C++ is to interface with C code taking FILE*
parameters. Many people who learned C and/or C++ using stdio believe these functions are somehow superior. The main complaint is that format specifiers using stdio are so much shorter. Unfortunately, they are also error-prone and despite warnings pointing out inconsistencies between format specifiers and actual arguments I have yet to see a program which uses stdio non-trivial and correctly.
The one omission in IOstreams which stdio does better is that the scanf()
functions can do some interesting parsing. This can be added to IOstreams quite easily but it isn't part of the standard library (and it isn't as terse as the format specifiers).
Personally, I consider the drawbacks irrelevant compared to the advantages:
- type-safe reading and writing
- user-defined support for user-defined types
- support for user-defined sources and destinations
- to a lesser degree control over formatting of numerical types
Due to a series of articles and some extremely bad implementations of early IOstreams (some of which still seem to linger in popular platforms) the C++ streams have gained an incorrect reputation of being slow. Yes, it is possibe to make sure that they are a lot slower than stdio but is definitely possible to implement them with similar performance as stdio. There are a few easy performance mistakes the user needs to avoid, however:
- Do not use
std::endl
. Period. If you really mean to write a newline followed by a flush say so: out << '\n' << std::flush
. This is what std::endl
does but std::endl
is incorrectly used in the vaste majority of the cases with the unintended flush causing major performance problems.
- Make sure the library doesn't waste time keeping things in sync with stdio operations: call
std::sync_with_stdio(false);
unless you are mixing output to the standard stream object (std::cin
, etc. and stdin
, etc.). Although the effect is only required for the standard stream objects, there are bad implementations of IOstreams where this also affects file streams.