diff options
Diffstat (limited to 'examples/hello_strlcpy/getline.c')
-rw-r--r-- | examples/hello_strlcpy/getline.c | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/examples/hello_strlcpy/getline.c b/examples/hello_strlcpy/getline.c new file mode 100644 index 0000000..777f5c4 --- /dev/null +++ b/examples/hello_strlcpy/getline.c @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2007-2013 by Aleksey Cheusov + * + * See LICENSE file in the distribution. + */ + +#include <stdio.h> +#include <stdlib.h> + +#include "decls.h" + +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 = realloc (*lineptr, *n); + if (!*lineptr) + return -1; + } + + (*lineptr) [sz++] = (char) c; + if (c == '\n') + break; + } + + if (ferror (stdin)) + return (ssize_t) -1; + + if (!sz){ + if (feof (stdin)){ + return (ssize_t) -1; + }else if (!*n){ + *lineptr = malloc (1); + if (!*lineptr) + return -1; + + *n = 1; + } + } + + (*lineptr) [sz] = 0; + return sz; +} |