2008-01-31 Johannes Schmid <jhs@gnome.org>
[anjuta-git-plugin.git] / src / getline.c
blob73c47aa673fa2c43240cbb1c1c4fe829a380da6a
1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
2 /*
3 * getline.c Copyright (C) 2003 Alexander Nedotsukov
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the Free
7 * Software Foundation; either version 2 of the License, or (at your option)
8 * any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 #ifdef FREEBSD
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <errno.h>
26 /* GNU libc getline() compatibility */
28 int
29 getline(char** line, size_t* size, FILE* fp)
31 static const size_t line_grow_by = 80; /* in most texts line fits console */
32 int ch;
33 size_t i;
35 if (line == NULL || size == NULL || fp == NULL) { /* illegal call */
36 errno = EINVAL;
37 return -1;
39 if (*line == NULL && *size) { /* logically incorrect */
40 errno = EINVAL;
41 return -1;
44 i = 0;
45 while (1) {
46 ch = fgetc(fp);
47 if (ch == EOF)
48 break;
49 /* ensure bufer still large enough for ch and trailing null */
50 if ((*size - i) <= 1) {
51 *line = (char*)realloc(*line, *size += line_grow_by);
52 if (*line == NULL) {
53 errno = ENOMEM;
54 return -1;
57 *(*line + i++) = (char)ch;
58 if (ch == '\n')
59 break;
62 *(*line + i) = 0;
64 return ferror(fp) ? -1 : i;
67 #endif