home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / Add-Ons / MPW / MPW noweb 2.7 / src / c / getline.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-10-04  |  1.6 KB  |  58 lines  |  [TEXT/MPS ]

  1. #define START_SIZE 128                  /* initial buffer size */
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include "columns.h"
  7. #include "errors.h"
  8. #include "getline.h"
  9.  
  10. static char *buf1 = NULL, *buf2 = NULL; /* lines without, with tabs expanded */
  11. static buf_size = START_SIZE;           /* size of both buffers if non-NULL */
  12.  
  13. void new_buffers(void) {
  14.     checkptr(buf1 = (char *) realloc(buf1, buf_size));
  15.     checkptr(buf2 = (char *) realloc(buf2, buf_size));
  16. }
  17. char *getline (FILE *fp) {
  18.  
  19.     if (buf1==NULL) {
  20.         checkptr(buf1 = (char *) malloc (buf_size));
  21.         checkptr(buf2 = (char *) malloc (buf_size));
  22.     }
  23.     
  24.     buf1=fgets(buf1, buf_size, fp);
  25.     if (buf1==NULL) return buf1; /* end of file */
  26.     while (buf1[strlen(buf1)-1] != '\n') { /* failed to get whole line */
  27.         buf_size *= 2;
  28.         new_buffers();
  29.         if (fgets(buf1+strlen(buf1),buf_size-strlen(buf1),fp)==NULL)
  30.             return buf1; /* end of file */
  31.     }
  32.     return buf1;
  33. }
  34. char *getline_expand (FILE *fp) {
  35.     char *s, *t;
  36.     int width;
  37.  
  38.     if (getline(fp)==NULL) return NULL;
  39.     if (columnwidth(buf1) > buf_size - 1) {
  40.         while (columnwidth(buf1) > buf_size - 1) buf_size *= 2;
  41.         new_buffers();
  42.     }
  43.     s = buf1; t = buf2; width=0;
  44.     while (*s)
  45.         if (*s=='\t' && tabsize > 0) {
  46.             do {
  47.                 *t++ = ' '; width++;
  48.             } while (width % tabsize != 0);
  49.             s++;
  50.         } else if (*s == (char) 0xCA) {
  51.             *t++ = ' '; ++s; width++;
  52.         } else {
  53.             *t++ = *s++; width++;
  54.         }
  55.     *t='\0';
  56.     return buf2;
  57. }
  58.