home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / MYLINE.CPP < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  79 lines

  1. // +++Date last modified: 05-Jul-1997
  2.  
  3. // myLine.cpp
  4. //
  5. // 13 Jun 93   Init array[0] = NUL in case it is reference before use
  6. //             memcpy() adjusted to also copy terminating NUL from is.get()
  7. //             when extending buffer
  8. //
  9.  
  10. # include <iostream.h>
  11. # include "myLine.h"
  12. # if defined(_MSC_VER)
  13. #  include <memory.h>
  14. # else
  15. #  include <stdlib.h>
  16. # endif
  17.  
  18.     // Class implementation
  19.  
  20. myLine::myLine (short buflen)
  21.     : len(buflen), mybuf(new char[len]), xalloc(1)
  22. {
  23.     mybuf[0] = 0;
  24. }
  25.  
  26. myLine::myLine (char * usebuf, short buflen)
  27.     : len(buflen), mybuf(usebuf), xalloc(0)
  28. {
  29.     mybuf[0] = 0;
  30. }
  31.  
  32. myLine::~myLine (void)
  33. {
  34.     if (xalloc)
  35.         delete [] mybuf;
  36. }
  37.  
  38.  
  39. istream &
  40. operator>> (istream & is, myLine & l)
  41. {
  42. # if AUTO_GROW
  43.     if (!l.xalloc)              // It's not my buf, so it can't be grown
  44.     {
  45. # endif
  46.         is.get (l.mybuf, l.len);
  47.         if (is.peek() == '\n')
  48.             is.get();           // Remove newline from stream
  49. # if AUTO_GROW
  50.     }
  51.     else
  52.     {
  53.         int idx = 0;
  54.         l.mybuf[0] = 0;     // Terminate in case is.good() isn't
  55.         for (int eol = 0; !eol && is.good(); )
  56.         {
  57.             int toget = l.len - idx;
  58.             is.get (l.mybuf + idx, toget);
  59.             int chrs = is.gcount();
  60.             if (is.peek() == '\n')
  61.             {
  62.                 ++eol;       // Must be eol or eof
  63.                 is.get();    // Clear newline
  64.             }
  65.             else if (chrs)
  66.             {                // Extend buffer
  67.                 idx += chrs; // Add to index
  68.                 l.len = short(l.len + ALLOC_LEN);
  69.                 char * tmp = new char[l.len];
  70.                 memcpy (tmp, l.mybuf, idx + 1);
  71.                 delete [] l.mybuf;
  72.                 l.mybuf = tmp;
  73.             }
  74.         }
  75.     }
  76. # endif
  77.     return is;
  78. }
  79.