home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / IOSTUTOR.TXT < prev    next >
Text File  |  1997-07-05  |  13KB  |  263 lines

  1. +++Date last modified: 05-Jul-1997
  2.  
  3. PROLOGUE --------
  4.  
  5. This tutorial started out as a "small" example of how to interface an I/O
  6. object into the AT&T iostream classes currently provided with almost every
  7. C++ compiler. When I say "small", I mean just that - but the scope of the
  8. information I wanted to present really didn't fit well into that little hole,
  9. so it turned out a little larger than I had initially hoped. However, I think
  10. the effort was worth it - I know it was for me, since although I've done code
  11. which deals with ostream, I hadn't fooled at all with istream derived
  12. facilities, and learned some new things in the process.
  13.  
  14. I can't really cite any single reference on iostreams that might prove useful
  15. for those wanting to go further other than the AT&T iostreams reference
  16. manual (my copy is out on loan at the moment so I can't quote the ISBN
  17. number). I have never come across one which is more complete than this
  18. reference, and most other references (including documentation from MSC/C++C,
  19. Borland, IBM etc.) tend to quote from it fairly liberally, but lack any of
  20. the important information needed to put it all together. While Microsoft's
  21. C++ tutorial reference has some great hints for getting started in iostream
  22. manipulators, it lacks in providing any information on interfacing to the
  23. iostream classes themselves.
  24.  
  25. Hopefully the information I've provided below will make some sense. It is as
  26. complete as I could make it without really going overboard. Most of the
  27. ostream related code is gleaned from my own library, but the rest is brand
  28. new.
  29.  
  30. The text of this tutorial and the accompanying source code are donated to the
  31. public domain.
  32.  
  33.  
  34. Tutorial in iostreams ---------------------
  35.  
  36. This little project started out with the following aims:
  37.  
  38. A)  To define a simple input/output object, one that consumes bytes sent to
  39.     it and generates data for input into a sample program. It should there-
  40.     fore feature a "read" and "write" function.  The object created is simply
  41.     a loopback buffer - input is queued immediately for output in FIFO (first
  42.     in first out) fashion.
  43.  
  44. B)  To create a streams interface for this object, so that existing facili-
  45.     ties for I/O in the AT&T streams classes can be used directly in a
  46.     polymorphic fashion (ie. make use of C++ inheritance & virtual dispatch).
  47.  
  48.     Specifically, I wanted to demonstrate the following aspects of iostreams:
  49.  
  50.     - Use of buffered vs. unbuffered I/O
  51.  
  52.     - Using the streams buffer for both input and output operations.  (an
  53.       interface to iostream, rather than just istream or ostream)
  54.  
  55.     - How the put, get and putback buffers work
  56.  
  57. C)  To write a trivial application which uses both components and provide a
  58.     means of interactively demonstrating how it all works.
  59.  
  60.  
  61. A - The I/O Object ----------------
  62.  
  63. class Myio;
  64.  
  65. This class is simply a front-end for a circular buffer. Input bytes are added
  66. at the head, and read from the tail. It is fixed in size, set by the
  67. constructor.
  68.  
  69. Two read/write functions are provided to access any contained data:
  70.  
  71.     int Myio::read (char * buf, int max);
  72.     int Myio::write (char const * buf, int len);
  73.  
  74. These are both non-blocking calls which return the number of bytes read or
  75. written. They know nothing about line delineation - only about raw bytes, as
  76. would be the case for almost any I/O device.
  77.  
  78. In addition, an internal flag is maintained to indicate when a write results
  79. in a buffer 'overflow' (an attempt to write more bytes than will fit in the
  80. buffer) and 'underflow' (an attempt to read an empty buffer). These flags
  81. reflect the last write and read calls respectively, and are reset or set on
  82. each write or read call.  The members Myio::readok() and Myio::writeok()
  83. return the settings as a boolean value.
  84.  
  85. A Myio object can also optionally create a stream. It is created and comes
  86. into life when the member function Myio::stream() is called. If it was
  87. previously created, this function simply returns a reference to the existing
  88. stream. The stream, if it exists, is deleted by the destructor.
  89.  
  90. Myio's stream is an iostream, which inherits all of the abilities of both
  91. ostream (for output) and istream (for input), including all operators. This,
  92. of course, is the primary benefit of using streams!
  93.  
  94.  
  95. B -  The Streams Interface -----------------------
  96.  
  97. class Mystreambuf; class Mystreambase; class Mystream;
  98.  
  99. Three classes as above are used. Mystreambuf derives from streambuf, and is
  100. responsible for the input output operations and buffering on behalf of a Myio
  101. object.  Mystreambase is used as a base class for Mystream to assist in the
  102. initialisation of the (My)streambuf passed to the iostream constructor.
  103.  
  104. The iostream side is in fact very simple. Nothing really needs to be
  105. overridden, and all of the work is done in Mystreambuf, where all the action
  106. really takes place.
  107.  
  108. The relationship between the ios/stream classes and the streambuf family is
  109. one of delegation rather than inheritance. The user/application accesses
  110. streambuf I/O via the stream object, not directly.  A class diagram showing
  111. the basic iostream classes and our classes would look like:
  112.  
  113.  
  114.          _ istream _ / \ ios -- ostream -- iostream \ \ \ Mystream \_____
  115. Mystreambase _/ | | (owns) | streambuf -- Mystreambuf
  116.  
  117.  
  118. All relationships, except the one marked "(owns)", indicate inheritance. The
  119. 'owns' relationship is where the delegation occurs.  ios is inherited
  120. virtually, so that there is only one combined 'ios' object at the root of the
  121. streams inheritance tree.
  122.  
  123. Within Mystreambuf, we need to override the functions responsible for actual
  124. input and output.  But first, let's discuss how this streambuf works.
  125.  
  126. Mystreambuf uses a single buffer, using the default buffer size allocated for
  127. any streambuf (under most operating systems, this will be 1024 bytes). Since
  128. we are dealing with both input and output operations, and these operations
  129. are independent so far as the streambuf is concerned (as is the case with,
  130. for example, serial I/O, but *not* the case with files), the buffer is split
  131. into two; the first half is used for writing, the second for reading.
  132.  
  133. The buffer used for writing is called the "put" buffer. Nothing mysterious
  134. there - when full, streambuf::overflow() function is called, and via virtual
  135. dispatch calls our Mystreambuf::overflow() which takes the contents of the
  136. buffer and writes it to the output device.
  137.  
  138. The read - or "get" - buffer is slightly more complex. There are occasions in
  139. dealing with an input stream where it is convenient to know what's next
  140. without actually removing it from the stream.  That way, you can use the next
  141. character as an indication of what to do next. For example, if you're parsing
  142. a number, you want to know whether or not the next character is a valid
  143. digit, and stop parsing if it isn't. The read side therefore incorporates the
  144. idea of a "putback" buffer - after being read, the character can be placed
  145. back into the input stream.
  146.  
  147. The putback buffer is entirely the responsibility of any streambuf derived
  148. class. It most you need to support a one character putback buffer - it is not
  149. valid to remove, and then restore, more than one character from the stream.
  150. It is also not valid put 'putback' any character but the one that was the
  151. result of the last 'get'.  It really must be "put back", not any old
  152. character "pushed" (you could actually support 'pushing' data into the stream
  153. if you wanted to, but you shouldn't use putback to do it).
  154.  
  155. The get buffer is set up as:
  156.  
  157.     Offset 0 1 2 3 ....  n | | | | to end of buffer |
  158. +---+---+---+---------------------+ ^ ^ | +- Start of get buffer (where data
  159. is read in) | +- Where data is putback
  160.  
  161. Each time streambuf runs out of characters to give to its client, the
  162. underflow() function is called. This fills the get buffer (get buffer size -
  163. 1, starting at offset 1) and reserves the first byte in case the previously
  164. read character needs to be put back.
  165.  
  166. streambuf provides internal pointers into the put, get and putback areas. All
  167. of the I/O functions it provides handle these automatically. In our
  168. underflow() and overflow() functions, we need to set these pointers according
  169. to where and how much data is read in.
  170.  
  171. I mentioned above that in our case, the input & output streams are
  172. independant. That's not entirely the case - it may happen that when reading
  173. from the Myio buffer we run out of data and need additional data in the
  174. output stream buffer not yet written to Myio. We therefore flush the output
  175. stream before retrieving any data by calling overflow() directly from within
  176. underflow().
  177.  
  178. The sync() function is also overridden. This simply empties all buffers by
  179. flushing the output buffer and discarding any buffered input.
  180.  
  181.  
  182. C - The Application -----------------
  183.  
  184. The application itself is a simple menu, offering choice to send a line of
  185. output to the IO object (via its stream), read one in, and dump/display
  186. information both about the stream and Myio object.
  187.  
  188. This added two other classes to the project:
  189.  
  190.     - myApplication: the actual application, implemented as a class.  The
  191.       only way to go in C++. :-)
  192.  
  193.     - myList: a simple line input class, whose sole purpose in life is to
  194.       extract a linefeed delimited line from any istream object and return it
  195.       as a char const *.  (I posted this code last week, but have since fixed
  196.       one minor bug I found in the process of developing Myio).
  197.  
  198. A couple of subtle points - class myApplication uses a pointer to member
  199. function it its menu selection. This is not the only way of doing this of
  200. course, but I thought it was a good way of demonstrating a very C++ specific
  201. concept, operator ->*, which does not exist at all in C.
  202.  
  203. Additional notes are included in the source comments.
  204.  
  205.  
  206. Making the application ----------------------
  207.  
  208. Hopefully this is a fairly simple thing to do - just compile the modules:
  209.  
  210.     Myiodemo.cpp Myio.cpp Mystream.cpp myLine.cpp
  211.  
  212. and link them together. A simple makefile is provided - take a look at the
  213. definitions at the top, adjust as desired, and type "make" (or nmake). If you
  214. use any of Borland's compilers, just add the above files to a new project
  215. called "Myiodemo.PRJ", set it to produce a .EXE (*not* Windows or PM based)
  216. and press F9.
  217.  
  218. Assuming a C++ compiler compatible with cfront 2.1 and the presence of an
  219. iostreams 1.2 library, the only non-portable part of this app is the use of
  220. getch() from conio.h. This isn't easily provided under a UNIX system. You can
  221. either fudge it by writing a getch() which switches into/out of 'raw' mode,
  222. or use getchar() and clear everything up to and including a CR or NL after
  223. the first character (the user still has to hit CR for input to get to the
  224. program).
  225.  
  226.  
  227.  
  228. EPILOGUE --------
  229.  
  230. Just some notes as to use of this code. If you need an output or input only
  231. class, then you use ostream or istream wherever iostream is mentioned in this
  232. example.  Also, if you use buffered mode (you can support it or not - you can
  233. even ignore the streambuf setting at your discretion), then you can use the
  234. entire buffer rather than just half each for input output.
  235.  
  236. If you interface to an input only object, you only need to override
  237. streambuf::underflow(). Conversely, you override streambuf::overflow() for an
  238. output only object. I have noticed that *some* implementations of iostreams
  239. define the overflow() and underflow() methods as pure virtual functions,
  240. whereas the AT&T default defines each as simply returning EOF.
  241.  
  242. If portability is any concern, you may need to override the function you
  243. aren't using in this fashion. The default sync() simply returns 0 (success),
  244. but again, this is sometimes defined as a pure virtual, so you may need to
  245. define it in your implementation.
  246.  
  247. In some cases, you may wish to "switch" between unbuffered and buffered
  248. modes. This is easily done by defining a function in Mystream which does it,
  249. and this object is of course accessible in your I/O object (in this case
  250. Myio). The only thing you need to remember is to flush all the buffers by
  251. calling sync() when switching from buffered to unbuffered mode.
  252.  
  253. Note also that some streambuf constructors take an existing buffer. This
  254. means that you can use buffers already provided in your I/O object directly
  255. rather than being forced to "double buffer" anything.  Your buffer can also
  256. be any size you like, subject to memory and other architecture constraints.
  257.  
  258.  
  259. Enjoy!
  260.  
  261. David Nugent - 3:632/348@fidonet.org
  262. Moderator ('93-'94) of the FidoNet international C++ EchoMail conference
  263.