CS 3733 Operating Systems, Spring 2000 Assignment 1 readln.c


#include < stdio.h >
#include < stdlib.h >
#include < unistd.h >
#include < string.h >

#define BUFSIZE 10
static int number_of_lines = 0;
static int number_of_mallocs = 0;
static int longest_line = 0;
static int largest_bufsize = 0;

char *readln(int fd) {

   char *buf;                /* this is where we put the line */
   char *bufsave;            /* saves a pointer to the old buffer */
   int bytes_left;           /* space left in allocated buffer */
   int bytes_read;           /* number of bytes read so far */
   int this_read;            /* number of bytes in the current read */
   int bufsize;              /* current size of the buffer, buf */
   int num_mallocs = 1;      /* number of mallocs done */

   bufsize = BUFSIZE;
   buf = (char *)malloc(bufsize);
   if (buf == NULL) return NULL;
   bytes_left = bufsize;
   bytes_read = 0;

   for (; ;) {
      if (bytes_left < 2) {
         bufsave = buf;
         buf = realloc(buf,bufsize*2);
         num_mallocs++;
         if (number_of_mallocs < num_mallocs)
            number_of_mallocs = num_mallocs;
         if (buf == NULL) {
            free(bufsave);
            return NULL;
         }
         bytes_left = bytes_left + bufsize;
         bufsize = 2*bufsize;
         if (largest_bufsize < bufsize)
            largest_bufsize = bufsize;
      }
      this_read = read(fd,buf+bytes_read,1);
      if (this_read < = 0) {       /* read error and end of file are the same */
         if (bytes_read == 0) {
            free(buf);
            return NULL;
         }
         *(buf+bytes_read) = 0;
         if (bytes_read > longest_line)
            longest_line = bytes_read;
         return buf;
      }
      if (*(buf+bytes_read) == 0)
         continue;
      bytes_left--;
      bytes_read++;
      if (*(buf+bytes_read - 1) == '\n') {
         *(buf+bytes_read) = 0;
         if (bytes_read > longest_line)
            longest_line = bytes_read;
         number_of_lines++;
         return buf;
      }
   }
/*NOTREACHED*/
}

int get_lines() {
   return number_of_lines;
}

int get_mallocs() {
   return number_of_mallocs;
}

int get_longest() {
   return longest_line;
}

int get_init() {
   return BUFSIZE;
}

int get_size() {
   return largest_bufsize;
}