Added debian/ from 1:1.10.2-1 debian package
[busybox4maemo] / libbb / fgets_str.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
4  *
5  * Copyright (C) many different people.
6  * If you wrote this, please acknowledge your work.
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
9  */
10
11 #include "libbb.h"
12
13 static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string, int chop_off)
14 {
15         char *linebuf = NULL;
16         const int term_length = strlen(terminating_string);
17         int end_string_offset;
18         int linebufsz = 0;
19         int idx = 0;
20         int ch;
21
22         while (1) {
23                 ch = fgetc(file);
24                 if (ch == EOF) {
25                         if (idx == 0)
26                                 return linebuf; /* NULL */
27                         break;
28                 }
29
30                 if (idx >= linebufsz) {
31                         linebufsz += 200;
32                         linebuf = xrealloc(linebuf, linebufsz);
33                 }
34
35                 linebuf[idx] = ch;
36                 idx++;
37
38                 /* Check for terminating string */
39                 end_string_offset = idx - term_length;
40                 if (end_string_offset >= 0
41                  && memcmp(&linebuf[end_string_offset], terminating_string, term_length) == 0
42                 ) {
43                         if (chop_off)
44                                 idx -= term_length;
45                         break;
46                 }
47         }
48         /* Grow/shrink *first*, then store NUL */
49         linebuf = xrealloc(linebuf, idx + 1);
50         linebuf[idx] = '\0';
51         return linebuf;
52 }
53
54 /* Read up to TERMINATING_STRING from FILE and return it,
55  * including terminating string.
56  * Non-terminated string can be returned if EOF is reached.
57  * Return NULL if EOF is reached immediately.  */
58 char *xmalloc_fgets_str(FILE *file, const char *terminating_string)
59 {
60         return xmalloc_fgets_internal(file, terminating_string, 0);
61 }
62
63 char *xmalloc_fgetline_str(FILE *file, const char *terminating_string)
64 {
65         return xmalloc_fgets_internal(file, terminating_string, 1);
66 }