1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
/*
* Copyright (c) 2007-2014 by Aleksey Cheusov
* See LICENSE file in the distribution.
*/
#include <stdio.h>
#include <stdlib.h>
ssize_t
getline(char** lineptr, size_t* n, FILE* stream);
ssize_t
getline(char** lineptr, size_t* n, FILE* stream)
{
int c;
size_t sz = 0;
while (c = getc (stream), c != EOF){
if (sz+1 >= *n){
/* +2 is for `c' and 0-terminator */
*n = *n * 3 / 2 + 2;
*lineptr = (char *) realloc (*lineptr, *n);
if (!*lineptr)
return -1;
}
(*lineptr) [sz++] = (char) c;
if (c == '\n')
break;
}
if (ferror (stream))
return (ssize_t) -1;
if (!sz){
if (feof (stream)){
return (ssize_t) -1;
}else if (!*n){
*lineptr = (char *) malloc (1);
if (!*lineptr)
return -1;
*n = 1;
}
}
(*lineptr) [sz] = 0;
return sz;
}
|