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