home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 2 / 2032 / getline.c < prev    next >
C/C++ Source or Header  |  1990-12-28  |  2KB  |  92 lines

  1. /*
  2.  * this was mercilessly stolen from rn
  3.  */
  4.  
  5. #include <stdio.h>
  6. #ifndef AIX        /* AIX doesn't have malloc.h.  Oh well... */
  7. #include <malloc.h>
  8. #endif
  9.  
  10. typedef unsigned int    MEM_SIZE;
  11. #ifdef NOLINEBUF
  12. #define FLUSH ,fflush(stdout)
  13. #else
  14. #define FLUSH
  15. #endif
  16.  
  17. /* just like fgets but will make bigger buffer as necessary */
  18.  
  19. char *
  20. get_a_line(original_buffer, buffer_length, fp)
  21.      char *original_buffer;
  22.      register int buffer_length;
  23.      FILE *fp;
  24. {
  25.   register int bufix = 0;
  26.   register int nextch;
  27.   register char *some_buffer_or_other = original_buffer;
  28.   char *safemalloc(), *saferealloc();
  29.   
  30.   do {
  31.     if (bufix >= buffer_length) {
  32.       buffer_length *= 2;
  33.       if (some_buffer_or_other == original_buffer) {
  34.     /* currently static? */
  35.     some_buffer_or_other = safemalloc((MEM_SIZE) buffer_length + 1);
  36.     strncpy(some_buffer_or_other, original_buffer, buffer_length / 2);
  37.     /* so we must copy it */
  38.       } else {    /* just grow in place, if possible */
  39.     some_buffer_or_other = saferealloc(some_buffer_or_other,
  40.                        (MEM_SIZE) buffer_length + 1);
  41.       }
  42.     }
  43.     if ((nextch = getc(fp)) == EOF)
  44.       return ((char *) NULL);
  45.     some_buffer_or_other[bufix++] = (char) nextch;
  46.   } while (nextch && nextch != '\n');
  47.   some_buffer_or_other[bufix] = '\0';
  48.   return some_buffer_or_other;
  49. }
  50.  
  51. static char nomem[] = "annejones: out of memory!\n";
  52.  
  53. /* paranoid version of safemalloc */
  54.  
  55. char *
  56. safemalloc(size)
  57.      MEM_SIZE size;
  58. {
  59.   char *ptr;
  60.   extern char *malloc();
  61.   
  62.   ptr = malloc(size ? size : 1);    /* safemalloc(0) is NASTY on our
  63.                        system */
  64.   if (ptr != (char *) NULL)
  65.     return ptr;
  66.   else {
  67.     fputs(nomem, stdout) FLUSH;
  68.     exit(0);
  69.   }
  70.   /* NOTREACHED */
  71. }
  72.  
  73. /* paranoid version of realloc */
  74. char *
  75. saferealloc(where, size)
  76.      char *where;
  77.      MEM_SIZE size;
  78. {
  79.   char *ptr;
  80.   extern char *realloc();
  81.   
  82.   ptr = realloc(where, size ? size : 1);
  83.  
  84.   if (ptr != (char *) NULL)
  85.     return ptr;
  86.   else {
  87.     fputs(nomem, stdout) FLUSH;
  88.     exit(0);
  89.   }
  90.   /* NOTREACHED */
  91. }
  92.