xref: /netbsd-src/external/gpl3/gcc.old/dist/libstdc++-v3/doc/xml/manual/io.xml (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1<chapter xmlns="http://docbook.org/ns/docbook" version="5.0"
2	 xml:id="std.io" xreflabel="Input and Output">
3<?dbhtml filename="io.html"?>
4
5<info><title>
6  Input and Output
7  <indexterm><primary>Input and Output</primary></indexterm>
8</title>
9  <keywordset>
10    <keyword>ISO C++</keyword>
11    <keyword>library</keyword>
12  </keywordset>
13</info>
14
15
16
17<!-- Sect1 01 : Iostream Objects -->
18<section xml:id="std.io.objects" xreflabel="IO Objects"><info><title>Iostream Objects</title></info>
19<?dbhtml filename="iostream_objects.html"?>
20
21
22   <para>To minimize the time you have to wait on the compiler, it's good to
23      only include the headers you really need.  Many people simply include
24      &lt;iostream&gt; when they don't need to -- and that can <emphasis>penalize
25      your runtime as well.</emphasis>  Here are some tips on which header to use
26      for which situations, starting with the simplest.
27   </para>
28   <para><emphasis>&lt;iosfwd&gt;</emphasis> should be included whenever you simply
29      need the <emphasis>name</emphasis> of an I/O-related class, such as
30      "ofstream" or "basic_streambuf".  Like the name
31      implies, these are forward declarations.  (A word to all you fellow
32      old school programmers:  trying to forward declare classes like
33      "class istream;" won't work.  Look in the iosfwd header if
34      you'd like to know why.)  For example,
35   </para>
36   <programlisting>
37    #include &lt;iosfwd&gt;
38
39    class MyClass
40    {
41	....
42	std::ifstream&amp;   input_file;
43    };
44
45    extern std::ostream&amp; operator&lt;&lt; (std::ostream&amp;, MyClass&amp;);
46   </programlisting>
47   <para><emphasis>&lt;ios&gt;</emphasis> declares the base classes for the entire
48      I/O stream hierarchy, std::ios_base and std::basic_ios&lt;charT&gt;, the
49      counting types std::streamoff and std::streamsize, the file
50      positioning type std::fpos, and the various manipulators like
51      std::hex, std::fixed, std::noshowbase, and so forth.
52   </para>
53   <para>The ios_base class is what holds the format flags, the state flags,
54      and the functions which change them (setf(), width(), precision(),
55      etc).  You can also store extra data and register callback functions
56      through ios_base, but that has been historically underused.  Anything
57      which doesn't depend on the type of characters stored is consolidated
58      here.
59   </para>
60   <para>The template class basic_ios is the highest template class in the
61      hierarchy; it is the first one depending on the character type, and
62      holds all general state associated with that type:  the pointer to the
63      polymorphic stream buffer, the facet information, etc.
64   </para>
65   <para><emphasis>&lt;streambuf&gt;</emphasis> declares the template class
66      basic_streambuf, and two standard instantiations, streambuf and
67      wstreambuf.  If you need to work with the vastly useful and capable
68      stream buffer classes, e.g., to create a new form of storage
69      transport, this header is the one to include.
70   </para>
71   <para><emphasis>&lt;istream&gt;</emphasis>/<emphasis>&lt;ostream&gt;</emphasis> are
72      the headers to include when you are using the &gt;&gt;/&lt;&lt;
73      interface, or any of the other abstract stream formatting functions.
74      For example,
75   </para>
76   <programlisting>
77    #include &lt;istream&gt;
78
79    std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, MyClass&amp; c)
80    {
81       return os &lt;&lt; c.data1() &lt;&lt; c.data2();
82    }
83   </programlisting>
84   <para>The std::istream and std::ostream classes are the abstract parents of
85      the various concrete implementations.  If you are only using the
86      interfaces, then you only need to use the appropriate interface header.
87   </para>
88   <para><emphasis>&lt;iomanip&gt;</emphasis> provides "extractors and inserters
89      that alter information maintained by class ios_base and its derived
90      classes," such as std::setprecision and std::setw.  If you need
91      to write expressions like <code>os &lt;&lt; setw(3);</code> or
92      <code>is &gt;&gt; setbase(8);</code>, you must include &lt;iomanip&gt;.
93   </para>
94   <para><emphasis>&lt;sstream&gt;</emphasis>/<emphasis>&lt;fstream&gt;</emphasis>
95      declare the six stringstream and fstream classes.  As they are the
96      standard concrete descendants of istream and ostream, you will already
97      know about them.
98   </para>
99   <para>Finally, <emphasis>&lt;iostream&gt;</emphasis> provides the eight standard
100      global objects (cin, cout, etc).  To do this correctly, this header
101      also provides the contents of the &lt;istream&gt; and &lt;ostream&gt;
102      headers, but nothing else.  The contents of this header look like
103   </para>
104   <programlisting>
105    #include &lt;ostream&gt;
106    #include &lt;istream&gt;
107
108    namespace std
109    {
110	extern istream cin;
111	extern ostream cout;
112	....
113
114	// this is explained below
115	<emphasis>static ios_base::Init __foo;</emphasis>    // not its real name
116    }
117   </programlisting>
118   <para>Now, the runtime penalty mentioned previously:  the global objects
119      must be initialized before any of your own code uses them; this is
120      guaranteed by the standard.  Like any other global object, they must
121      be initialized once and only once.  This is typically done with a
122      construct like the one above, and the nested class ios_base::Init is
123      specified in the standard for just this reason.
124   </para>
125   <para>How does it work?  Because the header is included before any of your
126      code, the <emphasis>__foo</emphasis> object is constructed before any of
127      your objects.  (Global objects are built in the order in which they
128      are declared, and destroyed in reverse order.)  The first time the
129      constructor runs, the eight stream objects are set up.
130   </para>
131   <para>The <code>static</code> keyword means that each object file compiled
132      from a source file containing &lt;iostream&gt; will have its own
133      private copy of <emphasis>__foo</emphasis>.  There is no specified order
134      of construction across object files (it's one of those pesky NP
135      problems that make life so interesting), so one copy in each object
136      file means that the stream objects are guaranteed to be set up before
137      any of your code which uses them could run, thereby meeting the
138      requirements of the standard.
139   </para>
140   <para>The penalty, of course, is that after the first copy of
141      <emphasis>__foo</emphasis> is constructed, all the others are just wasted
142      processor time.  The time spent is merely for an increment-and-test
143      inside a function call, but over several dozen or hundreds of object
144      files, that time can add up.  (It's not in a tight loop, either.)
145   </para>
146   <para>The lesson?  Only include &lt;iostream&gt; when you need to use one of
147      the standard objects in that source file; you'll pay less startup
148      time.  Only include the header files you need to in general; your
149      compile times will go down when there's less parsing work to do.
150   </para>
151
152</section>
153
154<!-- Sect1 02 : Stream Buffers -->
155<section xml:id="std.io.streambufs" xreflabel="Stream Buffers"><info><title>Stream Buffers</title></info>
156<?dbhtml filename="streambufs.html"?>
157
158
159  <section xml:id="io.streambuf.derived" xreflabel="Derived streambuf Classes"><info><title>Derived streambuf Classes</title></info>
160
161    <para>
162    </para>
163
164   <para>Creating your own stream buffers for I/O can be remarkably easy.
165      If you are interested in doing so, we highly recommend two very
166      excellent books:
167      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.angelikalanger.com/iostreams.html">Standard C++
168      IOStreams and Locales</link> by Langer and Kreft, ISBN 0-201-18395-1, and
169      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.josuttis.com/libbook/">The C++ Standard Library</link>
170      by Nicolai Josuttis, ISBN 0-201-37926-0.  Both are published by
171      Addison-Wesley, who isn't paying us a cent for saying that, honest.
172   </para>
173   <para>Here is a simple example, io/outbuf1, from the Josuttis text.  It
174      transforms everything sent through it to uppercase.  This version
175      assumes many things about the nature of the character type being
176      used (for more information, read the books or the newsgroups):
177   </para>
178   <programlisting>
179    #include &lt;iostream&gt;
180    #include &lt;streambuf&gt;
181    #include &lt;locale&gt;
182    #include &lt;cstdio&gt;
183
184    class outbuf : public std::streambuf
185    {
186      protected:
187	/* central output function
188	 * - print characters in uppercase mode
189	 */
190	virtual int_type overflow (int_type c) {
191	    if (c != EOF) {
192		// convert lowercase to uppercase
193		c = std::toupper(static_cast&lt;char&gt;(c),getloc());
194
195		// and write the character to the standard output
196		if (putchar(c) == EOF) {
197		    return EOF;
198		}
199	    }
200	    return c;
201	}
202    };
203
204    int main()
205    {
206	// create special output buffer
207	outbuf ob;
208	// initialize output stream with that output buffer
209	std::ostream out(&amp;ob);
210
211	out &lt;&lt; "31 hexadecimal: "
212	    &lt;&lt; std::hex &lt;&lt; 31 &lt;&lt; std::endl;
213	return 0;
214    }
215   </programlisting>
216   <para>Try it yourself!  More examples can be found in 3.1.x code, in
217      <code>include/ext/*_filebuf.h</code>, and in this article by James Kanze:
218      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://kanze.james.neuf.fr/articles/fltrsbf1.html">Filtering
219      Streambufs</link>.
220   </para>
221
222  </section>
223
224  <section xml:id="io.streambuf.buffering" xreflabel="Buffering"><info><title>Buffering</title></info>
225
226   <para>First, are you sure that you understand buffering?  Particularly
227      the fact that C++ may not, in fact, have anything to do with it?
228   </para>
229   <para>The rules for buffering can be a little odd, but they aren't any
230      different from those of C.  (Maybe that's why they can be a bit
231      odd.)  Many people think that writing a newline to an output
232      stream automatically flushes the output buffer.  This is true only
233      when the output stream is, in fact, a terminal and not a file
234      or some other device -- and <emphasis>that</emphasis> may not even be true
235      since C++ says nothing about files nor terminals.  All of that is
236      system-dependent.  (The "newline-buffer-flushing only occurring
237      on terminals" thing is mostly true on Unix systems, though.)
238   </para>
239   <para>Some people also believe that sending <code>endl</code> down an
240      output stream only writes a newline.  This is incorrect; after a
241      newline is written, the buffer is also flushed.  Perhaps this
242      is the effect you want when writing to a screen -- get the text
243      out as soon as possible, etc -- but the buffering is largely
244      wasted when doing this to a file:
245   </para>
246   <programlisting>
247   output &lt;&lt; "a line of text" &lt;&lt; endl;
248   output &lt;&lt; some_data_variable &lt;&lt; endl;
249   output &lt;&lt; "another line of text" &lt;&lt; endl; </programlisting>
250   <para>The proper thing to do in this case to just write the data out
251      and let the libraries and the system worry about the buffering.
252      If you need a newline, just write a newline:
253   </para>
254   <programlisting>
255   output &lt;&lt; "a line of text\n"
256	  &lt;&lt; some_data_variable &lt;&lt; '\n'
257	  &lt;&lt; "another line of text\n"; </programlisting>
258   <para>I have also joined the output statements into a single statement.
259      You could make the code prettier by moving the single newline to
260      the start of the quoted text on the last line, for example.
261   </para>
262   <para>If you do need to flush the buffer above, you can send an
263      <code>endl</code> if you also need a newline, or just flush the buffer
264      yourself:
265   </para>
266   <programlisting>
267   output &lt;&lt; ...... &lt;&lt; flush;    // can use std::flush manipulator
268   output.flush();               // or call a member fn </programlisting>
269   <para>On the other hand, there are times when writing to a file should
270      be like writing to standard error; no buffering should be done
271      because the data needs to appear quickly (a prime example is a
272      log file for security-related information).  The way to do this is
273      just to turn off the buffering <emphasis>before any I/O operations at
274      all</emphasis> have been done (note that opening counts as an I/O operation):
275   </para>
276   <programlisting>
277   std::ofstream    os;
278   std::ifstream    is;
279   int   i;
280
281   os.rdbuf()-&gt;pubsetbuf(0,0);
282   is.rdbuf()-&gt;pubsetbuf(0,0);
283
284   os.open("/foo/bar/baz");
285   is.open("/qux/quux/quuux");
286   ...
287   os &lt;&lt; "this data is written immediately\n";
288   is &gt;&gt; i;   // and this will probably cause a disk read </programlisting>
289   <para>Since all aspects of buffering are handled by a streambuf-derived
290      member, it is necessary to get at that member with <code>rdbuf()</code>.
291      Then the public version of <code>setbuf</code> can be called.  The
292      arguments are the same as those for the Standard C I/O Library
293      function (a buffer area followed by its size).
294   </para>
295   <para>A great deal of this is implementation-dependent.  For example,
296      <code>streambuf</code> does not specify any actions for its own
297      <code>setbuf()</code>-ish functions; the classes derived from
298      <code>streambuf</code> each define behavior that "makes
299      sense" for that class:  an argument of (0,0) turns off buffering
300      for <code>filebuf</code> but does nothing at all for its siblings
301      <code>stringbuf</code> and <code>strstreambuf</code>, and specifying
302      anything other than (0,0) has varying effects.
303      User-defined classes derived from <code>streambuf</code> can
304      do whatever they want.  (For <code>filebuf</code> and arguments for
305      <code>(p,s)</code> other than zeros, libstdc++ does what you'd expect:
306      the first <code>s</code> bytes of <code>p</code> are used as a buffer,
307      which you must allocate and deallocate.)
308   </para>
309   <para>A last reminder:  there are usually more buffers involved than
310      just those at the language/library level.  Kernel buffers, disk
311      buffers, and the like will also have an effect.  Inspecting and
312      changing those are system-dependent.
313   </para>
314
315  </section>
316</section>
317
318<!-- Sect1 03 : Memory-based Streams -->
319<section xml:id="std.io.memstreams" xreflabel="Memory Streams"><info><title>Memory Based Streams</title></info>
320<?dbhtml filename="stringstreams.html"?>
321
322  <section xml:id="std.io.memstreams.compat" xreflabel="Compatibility strstream"><info><title>Compatibility With strstream</title></info>
323
324    <para>
325    </para>
326   <para>Stringstreams (defined in the header <code>&lt;sstream&gt;</code>)
327      are in this author's opinion one of the coolest things since
328      sliced time.  An example of their use is in the Received Wisdom
329      section for Sect1 21 (Strings),
330      <link linkend="strings.string.Cstring"> describing how to
331      format strings</link>.
332   </para>
333   <para>The quick definition is:  they are siblings of ifstream and ofstream,
334      and they do for <code>std::string</code> what their siblings do for
335      files.  All that work you put into writing <code>&lt;&lt;</code> and
336      <code>&gt;&gt;</code> functions for your classes now pays off
337      <emphasis>again!</emphasis>  Need to format a string before passing the string
338      to a function?  Send your stuff via <code>&lt;&lt;</code> to an
339      ostringstream.  You've read a string as input and need to parse it?
340      Initialize an istringstream with that string, and then pull pieces
341      out of it with <code>&gt;&gt;</code>.  Have a stringstream and need to
342      get a copy of the string inside?  Just call the <code>str()</code>
343      member function.
344   </para>
345   <para>This only works if you've written your
346      <code>&lt;&lt;</code>/<code>&gt;&gt;</code> functions correctly, though,
347      and correctly means that they take istreams and ostreams as
348      parameters, not i<emphasis>f</emphasis>streams and o<emphasis>f</emphasis>streams.  If they
349      take the latter, then your I/O operators will work fine with
350      file streams, but with nothing else -- including stringstreams.
351   </para>
352   <para>If you are a user of the strstream classes, you need to update
353      your code.  You don't have to explicitly append <code>ends</code> to
354      terminate the C-style character array, you don't have to mess with
355      "freezing" functions, and you don't have to manage the
356      memory yourself.  The strstreams have been officially deprecated,
357      which means that 1) future revisions of the C++ Standard won't
358      support them, and 2) if you use them, people will laugh at you.
359   </para>
360
361
362  </section>
363</section>
364
365<!-- Sect1 04 : File-based Streams -->
366<section xml:id="std.io.filestreams" xreflabel="File Streams"><info><title>File Based Streams</title></info>
367<?dbhtml filename="fstreams.html"?>
368
369
370  <section xml:id="std.io.filestreams.copying_a_file" xreflabel="Copying a File"><info><title>Copying a File</title></info>
371
372  <para>
373  </para>
374
375   <para>So you want to copy a file quickly and easily, and most important,
376      completely portably.  And since this is C++, you have an open
377      ifstream (call it IN) and an open ofstream (call it OUT):
378   </para>
379   <programlisting>
380   #include &lt;fstream&gt;
381
382   std::ifstream  IN ("input_file");
383   std::ofstream  OUT ("output_file"); </programlisting>
384   <para>Here's the easiest way to get it completely wrong:
385   </para>
386   <programlisting>
387   OUT &lt;&lt; IN;</programlisting>
388   <para>For those of you who don't already know why this doesn't work
389      (probably from having done it before), I invite you to quickly
390      create a simple text file called "input_file" containing
391      the sentence
392   </para>
393      <programlisting>
394      The quick brown fox jumped over the lazy dog.</programlisting>
395   <para>surrounded by blank lines.  Code it up and try it.  The contents
396      of "output_file" may surprise you.
397   </para>
398   <para>Seriously, go do it.  Get surprised, then come back.  It's worth it.
399   </para>
400   <para>The thing to remember is that the <code>basic_[io]stream</code> classes
401      handle formatting, nothing else.  In chaptericular, they break up on
402      whitespace.  The actual reading, writing, and storing of data is
403      handled by the <code>basic_streambuf</code> family.  Fortunately, the
404      <code>operator&lt;&lt;</code> is overloaded to take an ostream and
405      a pointer-to-streambuf, in order to help with just this kind of
406      "dump the data verbatim" situation.
407   </para>
408   <para>Why a <emphasis>pointer</emphasis> to streambuf and not just a streambuf?  Well,
409      the [io]streams hold pointers (or references, depending on the
410      implementation) to their buffers, not the actual
411      buffers.  This allows polymorphic behavior on the chapter of the buffers
412      as well as the streams themselves.  The pointer is easily retrieved
413      using the <code>rdbuf()</code> member function.  Therefore, the easiest
414      way to copy the file is:
415   </para>
416   <programlisting>
417   OUT &lt;&lt; IN.rdbuf();</programlisting>
418   <para>So what <emphasis>was</emphasis> happening with OUT&lt;&lt;IN?  Undefined
419      behavior, since that chaptericular &lt;&lt; isn't defined by the Standard.
420      I have seen instances where it is implemented, but the character
421      extraction process removes all the whitespace, leaving you with no
422      blank lines and only "Thequickbrownfox...".  With
423      libraries that do not define that operator, IN (or one of IN's
424      member pointers) sometimes gets converted to a void*, and the output
425      file then contains a perfect text representation of a hexadecimal
426      address (quite a big surprise).  Others don't compile at all.
427   </para>
428   <para>Also note that none of this is specific to o<emphasis>*f*</emphasis>streams.
429      The operators shown above are all defined in the parent
430      basic_ostream class and are therefore available with all possible
431      descendants.
432   </para>
433
434  </section>
435
436  <section xml:id="std.io.filestreams.binary" xreflabel="Binary Input and Output"><info><title>Binary Input and Output</title></info>
437
438    <para>
439    </para>
440   <para>The first and most important thing to remember about binary I/O is
441      that opening a file with <code>ios::binary</code> is not, repeat
442      <emphasis>not</emphasis>, the only thing you have to do.  It is not a silver
443      bullet, and will not allow you to use the <code>&lt;&lt;/&gt;&gt;</code>
444      operators of the normal fstreams to do binary I/O.
445   </para>
446   <para>Sorry.  Them's the breaks.
447   </para>
448   <para>This isn't going to try and be a complete tutorial on reading and
449      writing binary files (because "binary"
450      covers a lot of ground), but we will try and clear
451      up a couple of misconceptions and common errors.
452   </para>
453   <para>First, <code>ios::binary</code> has exactly one defined effect, no more
454      and no less.  Normal text mode has to be concerned with the newline
455      characters, and the runtime system will translate between (for
456      example) '\n' and the appropriate end-of-line sequence (LF on Unix,
457      CRLF on DOS, CR on Macintosh, etc).  (There are other things that
458      normal mode does, but that's the most obvious.)  Opening a file in
459      binary mode disables this conversion, so reading a CRLF sequence
460      under Windows won't accidentally get mapped to a '\n' character, etc.
461      Binary mode is not supposed to suddenly give you a bitstream, and
462      if it is doing so in your program then you've discovered a bug in
463      your vendor's compiler (or some other chapter of the C++ implementation,
464      possibly the runtime system).
465   </para>
466   <para>Second, using <code>&lt;&lt;</code> to write and <code>&gt;&gt;</code> to
467      read isn't going to work with the standard file stream classes, even
468      if you use <code>skipws</code> during reading.  Why not?  Because
469      ifstream and ofstream exist for the purpose of <emphasis>formatting</emphasis>,
470      not reading and writing.  Their job is to interpret the data into
471      text characters, and that's exactly what you don't want to happen
472      during binary I/O.
473   </para>
474   <para>Third, using the <code>get()</code> and <code>put()/write()</code> member
475      functions still aren't guaranteed to help you.  These are
476      "unformatted" I/O functions, but still character-based.
477      (This may or may not be what you want, see below.)
478   </para>
479   <para>Notice how all the problems here are due to the inappropriate use
480      of <emphasis>formatting</emphasis> functions and classes to perform something
481      which <emphasis>requires</emphasis> that formatting not be done?  There are a
482      seemingly infinite number of solutions, and a few are listed here:
483   </para>
484   <itemizedlist>
485      <listitem>
486	<para><quote>Derive your own fstream-type classes and write your own
487	  &lt;&lt;/&gt;&gt; operators to do binary I/O on whatever data
488	  types you're using.</quote>
489	</para>
490	<para>
491	  This is a Bad Thing, because while
492	  the compiler would probably be just fine with it, other humans
493	  are going to be confused.  The overloaded bitshift operators
494	  have a well-defined meaning (formatting), and this breaks it.
495	</para>
496      </listitem>
497      <listitem>
498	<para>
499	  <quote>Build the file structure in memory, then
500	  <code>mmap()</code> the file and copy the
501	  structure.
502	</quote>
503	</para>
504	<para>
505	  Well, this is easy to make work, and easy to break, and is
506	  pretty equivalent to using <code>::read()</code> and
507	  <code>::write()</code> directly, and makes no use of the
508	  iostream library at all...
509	  </para>
510      </listitem>
511      <listitem>
512	<para>
513	  <quote>Use streambufs, that's what they're there for.</quote>
514	</para>
515	<para>
516	  While not trivial for the beginner, this is the best of all
517	  solutions.  The streambuf/filebuf layer is the layer that is
518	  responsible for actual I/O.  If you want to use the C++
519	  library for binary I/O, this is where you start.
520	</para>
521      </listitem>
522   </itemizedlist>
523   <para>How to go about using streambufs is a bit beyond the scope of this
524      document (at least for now), but while streambufs go a long way,
525      they still leave a couple of things up to you, the programmer.
526      As an example, byte ordering is completely between you and the
527      operating system, and you have to handle it yourself.
528   </para>
529   <para>Deriving a streambuf or filebuf
530      class from the standard ones, one that is specific to your data
531      types (or an abstraction thereof) is probably a good idea, and
532      lots of examples exist in journals and on Usenet.  Using the
533      standard filebufs directly (either by declaring your own or by
534      using the pointer returned from an fstream's <code>rdbuf()</code>)
535      is certainly feasible as well.
536   </para>
537   <para>One area that causes problems is trying to do bit-by-bit operations
538      with filebufs.  C++ is no different from C in this respect:  I/O
539      must be done at the byte level.  If you're trying to read or write
540      a few bits at a time, you're going about it the wrong way.  You
541      must read/write an integral number of bytes and then process the
542      bytes.  (For example, the streambuf functions take and return
543      variables of type <code>int_type</code>.)
544   </para>
545   <para>Another area of problems is opening text files in binary mode.
546      Generally, binary mode is intended for binary files, and opening
547      text files in binary mode means that you now have to deal with all of
548      those end-of-line and end-of-file problems that we mentioned before.
549   </para>
550   <para>
551      An instructive thread from comp.lang.c++.moderated delved off into
552      this topic starting more or less at
553      <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://groups.google.com/group/comp.std.c++/browse_thread/thread/f87b4abd7954a87/946a3eb9921e382d?q=comp.std.c%2B%2B+binary+iostream#946a3eb9921e382d">this</link>
554      post and continuing to the end of the thread. (The subject heading is "binary iostreams" on both comp.std.c++
555      and comp.lang.c++.moderated.) Take special note of the replies by James Kanze and Dietmar Kühl.
556   </para>
557    <para>Briefly, the problems of byte ordering and type sizes mean that
558      the unformatted functions like <code>ostream::put()</code> and
559      <code>istream::get()</code> cannot safely be used to communicate
560      between arbitrary programs, or across a network, or from one
561      invocation of a program to another invocation of the same program
562      on a different platform, etc.
563   </para>
564 </section>
565
566</section>
567
568<!-- Sect1 03 : Interacting with C -->
569<section xml:id="std.io.c" xreflabel="Interacting with C"><info><title>Interacting with C</title></info>
570<?dbhtml filename="io_and_c.html"?>
571
572
573
574  <section xml:id="std.io.c.FILE" xreflabel="Using FILE* and file descriptors"><info><title>Using FILE* and file descriptors</title></info>
575
576    <para>
577      See the <link linkend="manual.ext.io">extensions</link> for using
578      <type>FILE</type> and <type>file descriptors</type> with
579      <classname>ofstream</classname> and
580      <classname>ifstream</classname>.
581    </para>
582  </section>
583
584  <section xml:id="std.io.c.sync" xreflabel="Performance Issues"><info><title>Performance</title></info>
585
586    <para>
587      Pathetic Performance? Ditch C.
588    </para>
589   <para>It sounds like a flame on C, but it isn't.  Really.  Calm down.
590      I'm just saying it to get your attention.
591   </para>
592   <para>Because the C++ library includes the C library, both C-style and
593      C++-style I/O have to work at the same time.  For example:
594   </para>
595   <programlisting>
596     #include &lt;iostream&gt;
597     #include &lt;cstdio&gt;
598
599     std::cout &lt;&lt; "Hel";
600     std::printf ("lo, worl");
601     std::cout &lt;&lt; "d!\n";
602   </programlisting>
603   <para>This must do what you think it does.
604   </para>
605   <para>Alert members of the audience will immediately notice that buffering
606      is going to make a hash of the output unless special steps are taken.
607   </para>
608   <para>The special steps taken by libstdc++, at least for version 3.0,
609      involve doing very little buffering for the standard streams, leaving
610      most of the buffering to the underlying C library.  (This kind of
611      thing is tricky to get right.)
612      The upside is that correctness is ensured.  The downside is that
613      writing through <code>cout</code> can quite easily lead to awful
614      performance when the C++ I/O library is layered on top of the C I/O
615      library (as it is for 3.0 by default).  Some patches have been applied
616      which improve the situation for 3.1.
617   </para>
618   <para>However, the C and C++ standard streams only need to be kept in sync
619      when both libraries' facilities are in use.  If your program only uses
620      C++ I/O, then there's no need to sync with the C streams.  The right
621      thing to do in this case is to call
622   </para>
623   <programlisting>
624     #include <emphasis>any of the I/O headers such as ios, iostream, etc</emphasis>
625
626     std::ios::sync_with_stdio(false);
627   </programlisting>
628   <para>You must do this before performing any I/O via the C++ stream objects.
629      Once you call this, the C++ streams will operate independently of the
630      (unused) C streams.  For GCC 3.x, this means that <code>cout</code> and
631      company will become fully buffered on their own.
632   </para>
633   <para>Note, by the way, that the synchronization requirement only applies to
634      the standard streams (<code>cin</code>, <code>cout</code>,
635      <code>cerr</code>,
636      <code>clog</code>, and their wide-character counterchapters).  File stream
637      objects that you declare yourself have no such requirement and are fully
638      buffered.
639   </para>
640
641
642  </section>
643</section>
644
645</chapter>
646