OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libstdc++-v3/] [doc/] [xml/] [manual/] [io.xml] - Blame information for rev 742

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 742 jeremybenn
2
         xml:id="std.io" xreflabel="Input and Output">
3
4
 
5
</code></pre></td>
      </tr>
      <tr valign="middle">
         <td>6</td>
         <td></td>
         <td></td>
         <td class="code"><pre><code>  Input and Output</code></pre></td>
      </tr>
      <tr valign="middle">
         <td>7</td>
         <td></td>
         <td></td>
         <td class="code"><pre><code>  <indexterm><primary>Input and Output</primary></indexterm></code></pre></td>
      </tr>
      <tr valign="middle">
         <td>8</td>
         <td></td>
         <td></td>
         <td class="code"><pre><code>
9
  
10
    
11
      ISO C++
12
    
13
    
14
      library
15
    
16
  
17
18
 
19
 
20
 
21
22
Iostream Objects
23
24
 
25
 
26
   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
      <iostream> when they don't need to -- and that can penalize
29
      your runtime as well.  Here are some tips on which header to use
30
      for which situations, starting with the simplest.
31
   
32
   <iosfwd> should be included whenever you simply
33
      need the name 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
   
40
   
41
    #include <iosfwd>
42
 
43
    class MyClass
44
    {
45
        ....
46
        std::ifstream&   input_file;
47
    };
48
 
49
    extern std::ostream& operator<< (std::ostream&, MyClass&);
50
   
51
   <ios> declares the base classes for the entire
52
      I/O stream hierarchy, std::ios_base and std::basic_ios<charT>, 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
   
57
   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
   
64
   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
   
69
   <streambuf> 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
   
75
   <istream>/<ostream> are
76
      the headers to include when you are using the >>/<<
77
      interface, or any of the other abstract stream formatting functions.
78
      For example,
79
   
80
   
81
    #include <istream>
82
 
83
    std::ostream& operator<< (std::ostream& os, MyClass& c)
84
    {
85
       return os << c.data1() << c.data2();
86
    }
87
   
88
   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
   
92
   <iomanip> 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 os << setw(3); or
96
      is >> setbase(8);, you must include <iomanip>.
97
   
98
   <sstream>/<fstream>
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
   
103
   Finally, <iostream> provides the eight standard
104
      global objects (cin, cout, etc).  To do this correctly, this header
105
      also provides the contents of the <istream> and <ostream>
106
      headers, but nothing else.  The contents of this header look like
107
   
108
   
109
    #include <ostream>
110
    #include <istream>
111
 
112
    namespace std
113
    {
114
        extern istream cin;
115
        extern ostream cout;
116
        ....
117
 
118
        // this is explained below
119
        static ios_base::Init __foo;    // not its real name
120
    }
121
   
122
   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
   
129
   How does it work?  Because the header is included before any of your
130
      code, the __foo 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
   
135
   The static keyword means that each object file compiled
136
      from a source file containing <iostream> will have its own
137
      private copy of __foo.  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
   
144
   The penalty, of course, is that after the first copy of
145
      __foo 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
   
150
   The lesson?  Only include <iostream> 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
   
155
 
156
157
 
158
159
Stream Buffers
160
161
 
162
 
163
  
Derived streambuf Classes
164
 
165
    
166
    
167
 
168
   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
      Standard C++
172
      IOStreams and Locales by Langer and Kreft, ISBN 0-201-18395-1, and
173
      The C++ Standard Library
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
   
177
   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
   
182
   
183
    #include <iostream>
184
    #include <streambuf>
185
    #include <locale>
186
    #include <cstdio>
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<char>(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(&ob);
214
 
215
        out << "31 hexadecimal: "
216
            << std::hex << 31 << std::endl;
217
        return 0;
218
    }
219
   
220
   Try it yourself!  More examples can be found in 3.1.x code, in
221
      include/ext/*_filebuf.h, and in this article by James Kanze:
222
      Filtering
223
      Streambufs.
224
   
225
 
226
  
227
 
228
  
Buffering
229
 
230
   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
   
233
   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 that 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
   
243
   Some people also believe that sending endl 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
   
250
   
251
   output << "a line of text" << endl;
252
   output << some_data_variable << endl;
253
   output << "another line of text" << endl; 
254
   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
   
258
   
259
   output << "a line of text\n"
260
          << some_data_variable << '\n'
261
          << "another line of text\n"; 
262
   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
   
266
   If you do need to flush the buffer above, you can send an
267
      endl if you also need a newline, or just flush the buffer
268
      yourself:
269
   
270
   
271
   output << ...... << flush;    // can use std::flush manipulator
272
   output.flush();               // or call a member fn 
273
   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 before any I/O operations at
278
      all have been done (note that opening counts as an I/O operation):
279
   
280
   
281
   std::ofstream    os;
282
   std::ifstream    is;
283
   int   i;
284
 
285
   os.rdbuf()->pubsetbuf(0,0);
286
   is.rdbuf()->pubsetbuf(0,0);
287
 
288
   os.open("/foo/bar/baz");
289
   is.open("/qux/quux/quuux");
290
   ...
291
   os << "this data is written immediately\n";
292
   is >> i;   // and this will probably cause a disk read 
293
   Since all aspects of buffering are handled by a streambuf-derived
294
      member, it is necessary to get at that member with rdbuf().
295
      Then the public version of setbuf 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
   
299
   A great deal of this is implementation-dependent.  For example,
300
      streambuf does not specify any actions for its own
301
      setbuf()-ish functions; the classes derived from
302
      streambuf each define behavior that "makes
303
      sense" for that class:  an argument of (0,0) turns off buffering
304
      for filebuf but does nothing at all for its siblings
305
      stringbuf and strstreambuf, and specifying
306
      anything other than (0,0) has varying effects.
307
      User-defined classes derived from streambuf can
308
      do whatever they want.  (For filebuf and arguments for
309
      (p,s) other than zeros, libstdc++ does what you'd expect:
310
      the first s bytes of p are used as a buffer,
311
      which you must allocate and deallocate.)
312
   
313
   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
   
318
 
319
  
320
321
 
322
323
Memory Based Streams
324
325
 
326
  
Compatibility With strstream
327
 
328
    
329
    
330
   Stringstreams (defined in the header <sstream>)
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
       describing how to
335
      format strings.
336
   
337
   The quick definition is:  they are siblings of ifstream and ofstream,
338
      and they do for std::string what their siblings do for
339
      files.  All that work you put into writing << and
340
      >> functions for your classes now pays off
341
      again!  Need to format a string before passing the string
342
      to a function?  Send your stuff via << 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 >>.  Have a stringstream and need to
346
      get a copy of the string inside?  Just call the str()
347
      member function.
348
   
349
   This only works if you've written your
350
      <</>> functions correctly, though,
351
      and correctly means that they take istreams and ostreams as
352
      parameters, not ifstreams and ofstreams.  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
   
356
   If you are a user of the strstream classes, you need to update
357
      your code.  You don't have to explicitly append ends 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
   
364
 
365
 
366
  
367
368
 
369
370
File Based Streams
371
372
 
373
 
374
  
Copying a File
375
 
376
  
377
  
378
 
379
   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
   
383
   
384
   #include <fstream>
385
 
386
   std::ifstream  IN ("input_file");
387
   std::ofstream  OUT ("output_file"); 
388
   Here's the easiest way to get it completely wrong:
389
   
390
   
391
   OUT << IN;
392
   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
   
397
      
398
      The quick brown fox jumped over the lazy dog.
399
   surrounded by blank lines.  Code it up and try it.  The contents
400
      of "output_file" may surprise you.
401
   
402
   Seriously, go do it.  Get surprised, then come back.  It's worth it.
403
   
404
   The thing to remember is that the basic_[io]stream 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 basic_streambuf family.  Fortunately, the
408
      operator<< 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
   
412
   Why a pointer 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 rdbuf() member function.  Therefore, the easiest
418
      way to copy the file is:
419
   
420
   
421
   OUT << IN.rdbuf();
422
   So what was happening with OUT<<IN?  Undefined
423
      behavior, since that chaptericular << 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
   
432
   Also note that none of this is specific to o*f*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
   
437
 
438
  
439
 
440
  
Binary Input and Output
441
 
442
    
443
    
444
   The first and most important thing to remember about binary I/O is
445
      that opening a file with ios::binary is not, repeat
446
      not, the only thing you have to do.  It is not a silver
447
      bullet, and will not allow you to use the <</>>
448
      operators of the normal fstreams to do binary I/O.
449
   
450
   Sorry.  Them's the breaks.
451
   
452
   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
   
457
   First, ios::binary 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
   
470
   Second, using << to write and >> to
471
      read isn't going to work with the standard file stream classes, even
472
      if you use skipws during reading.  Why not?  Because
473
      ifstream and ofstream exist for the purpose of formatting,
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
   
478
   Third, using the get() and put()/write() 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
   
483
   Notice how all the problems here are due to the inappropriate use
484
      of formatting functions and classes to perform something
485
      which requires that formatting not be done?  There are a
486
      seemingly infinite number of solutions, and a few are listed here:
487
   
488
   
489
      
490
        Derive your own fstream-type classes and write your own
491
          <</>> operators to do binary I/O on whatever data
492
          types you're using.
493
        
494
        
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
        
500
      
501
      
502
        
503
          Build the file structure in memory, then
504
          mmap() the file and copy the
505
          structure.
506
        
507
        
508
        
509
          Well, this is easy to make work, and easy to break, and is
510
          pretty equivalent to using ::read() and
511
          ::write() directly, and makes no use of the
512
          iostream library at all...
513
          
514
      
515
      
516
        
517
          Use streambufs, that's what they're there for.
518
        
519
        
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
        
525
      
526
   
527
   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
   
533
   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 rdbuf())
539
      is certainly feasible as well.
540
   
541
   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 int_type.)
548
   
549
   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
   
554
   
555
      An instructive thread from comp.lang.c++.moderated delved off into
556
      this topic starting more or less at
557
      this
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
   
561
    Briefly, the problems of byte ordering and type sizes mean that
562
      the unformatted functions like ostream::put() and
563
      istream::get() 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
   
568
 
569
 
570
571
 
572
573
Interacting with C
574
575
 
576
 
577
 
578
  
Using FILE* and file descriptors
579
 
580
    
581
      See the extensions for using
582
      FILE and file descriptors with
583
      ofstream and
584
      ifstream.
585
    
586
  
587
 
588
  
Performance
589
 
590
    
591
      Pathetic Performance? Ditch C.
592
    
593
   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
   
596
   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
   
599
   
600
     #include <iostream>
601
     #include <cstdio>
602
 
603
     std::cout << "Hel";
604
     std::printf ("lo, worl");
605
     std::cout << "d!\n";
606
   
607
   This must do what you think it does.
608
   
609
   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
   
612
   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 cout 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
   
622
   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
   
627
   
628
     #include any of the I/O headers such as ios, iostream, etc
629
 
630
     std::ios::sync_with_stdio(false);
631
   
632
   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 cout and
635
      company will become fully buffered on their own.
636
   
637
   Note, by the way, that the synchronization requirement only applies to
638
      the standard streams (cin, cout,
639
      cerr,
640
      clog, and their wide-character counterchapters).  File stream
641
      objects that you declare yourself have no such requirement and are fully
642
      buffered.
643
   
644
 
645
 
646
  
647
648
 
649

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.