Blame lib/getline.c

Packit 0b5880
/*
Packit 0b5880
 * Check: a unit test framework for C
Packit 0b5880
 * Copyright (C) 2001, 2002 Arien Malec
Packit 0b5880
 *
Packit 0b5880
 * This library is free software; you can redistribute it and/or
Packit 0b5880
 * modify it under the terms of the GNU Lesser General Public
Packit 0b5880
 * License as published by the Free Software Foundation; either
Packit 0b5880
 * version 2.1 of the License, or (at your option) any later version.
Packit 0b5880
 *
Packit 0b5880
 * This library is distributed in the hope that it will be useful,
Packit 0b5880
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 0b5880
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit 0b5880
 * Lesser General Public License for more details.
Packit 0b5880
 *
Packit 0b5880
 * You should have received a copy of the GNU Lesser General Public
Packit 0b5880
 * License along with this library; if not, write to the
Packit 0b5880
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
Packit 0b5880
 * MA 02110-1301, USA.
Packit 0b5880
 */
Packit 0b5880
Packit 0b5880
#include "libcompat.h"
Packit 0b5880
#include <stdio.h>
Packit 0b5880
Packit 0b5880
#define INITIAL_SIZE 16
Packit 0b5880
#define DELIMITER '\n'
Packit 0b5880
Packit 0b5880
ssize_t getline(char **lineptr, size_t *n, FILE *stream)
Packit 0b5880
{
Packit 0b5880
     ssize_t written = 0;
Packit 0b5880
     int character;
Packit 0b5880
Packit 0b5880
     if(*lineptr == NULL || *n < INITIAL_SIZE)
Packit 0b5880
     {
Packit 0b5880
          free(*lineptr);
Packit 0b5880
          *lineptr = (char *)malloc(INITIAL_SIZE);
Packit 0b5880
          *n = INITIAL_SIZE;
Packit 0b5880
     }
Packit 0b5880
Packit 0b5880
     while( (character = fgetc(stream)) != EOF)
Packit 0b5880
     {
Packit 0b5880
          written += 1;
Packit 0b5880
          if(written >= *n)
Packit 0b5880
          {
Packit 0b5880
               *n = *n * 2;
Packit 0b5880
               *lineptr = realloc(*lineptr, *n);
Packit 0b5880
          }
Packit 0b5880
Packit 0b5880
          (*lineptr)[written-1] = character;
Packit 0b5880
Packit 0b5880
          if(character == DELIMITER)
Packit 0b5880
          {
Packit 0b5880
               break;
Packit 0b5880
          }
Packit 0b5880
     }
Packit 0b5880
Packit 0b5880
     (*lineptr)[written] = '\0';
Packit 0b5880
Packit 0b5880
     return written;
Packit 0b5880
}