Interacting with C

Using FILE* and file descriptors

See the extensions for using FILE and file descriptors with ofstream and ifstream.

Performance

Pathetic Performance? Ditch C.

It sounds like a flame on C, but it isn't. Really. Calm down. I'm just saying it to get your attention.

Because the C++ library includes the C library, both C-style and C++-style I/O have to work at the same time. For example:

     #include <iostream>
     #include <cstdio>

     std::cout << "Hel";
     std::printf ("lo, worl");
     std::cout << "d!\n";
   

This must do what you think it does.

Alert members of the audience will immediately notice that buffering is going to make a hash of the output unless special steps are taken.

The special steps taken by libstdc++, at least for version 3.0, involve doing very little buffering for the standard streams, leaving most of the buffering to the underlying C library. (This kind of thing is tricky to get right.) The upside is that correctness is ensured. The downside is that writing through cout can quite easily lead to awful performance when the C++ I/O library is layered on top of the C I/O library (as it is for 3.0 by default). Some patches have been applied which improve the situation for 3.1.

However, the C and C++ standard streams only need to be kept in sync when both libraries' facilities are in use. If your program only uses C++ I/O, then there's no need to sync with the C streams. The right thing to do in this case is to call

     #include any of the I/O headers such as ios, iostream, etc

     std::ios::sync_with_stdio(false);
   

You must do this before performing any I/O via the C++ stream objects. Once you call this, the C++ streams will operate independently of the (unused) C streams. For GCC 3.x, this means that cout and company will become fully buffered on their own.

Note, by the way, that the synchronization requirement only applies to the standard streams (cin, cout, cerr, clog, and their wide-character counterchapters). File stream objects that you declare yourself have no such requirement and are fully buffered.