typo fix
[busybox-git.git] / libbb / fgets_str.c
blobc884ef8af23bf00f31d990017f2a33ff853deb98
1 /* vi: set sw=4 ts=4: */
2 /*
3 * Utility routines.
5 * Copyright (C) many different people.
6 * If you wrote this, please acknowledge your work.
8 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9 */
10 #include "libbb.h"
12 static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string, int chop_off, size_t *maxsz_p)
14 char *linebuf = NULL;
15 const int term_length = strlen(terminating_string);
16 int end_string_offset;
17 int linebufsz = 0;
18 int idx = 0;
19 int ch;
20 size_t maxsz = maxsz_p ? *maxsz_p : INT_MAX - 4095;
22 while (1) {
23 ch = fgetc(file);
24 if (ch == EOF) {
25 if (idx == 0)
26 return linebuf; /* NULL */
27 break;
30 if (idx >= linebufsz) {
31 linebufsz += 200;
32 linebuf = xrealloc(linebuf, linebufsz);
33 if (idx >= maxsz) {
34 linebuf[idx] = ch;
35 idx++;
36 break;
40 linebuf[idx] = ch;
41 idx++;
43 /* Check for terminating string */
44 end_string_offset = idx - term_length;
45 if (end_string_offset >= 0
46 && memcmp(&linebuf[end_string_offset], terminating_string, term_length) == 0
47 ) {
48 if (chop_off)
49 idx -= term_length;
50 break;
53 /* Grow/shrink *first*, then store NUL */
54 linebuf = xrealloc(linebuf, idx + 1);
55 linebuf[idx] = '\0';
56 if (maxsz_p)
57 *maxsz_p = idx;
58 return linebuf;
61 /* Read up to TERMINATING_STRING from FILE and return it,
62 * including terminating string.
63 * Non-terminated string can be returned if EOF is reached.
64 * Return NULL if EOF is reached immediately. */
65 char* FAST_FUNC xmalloc_fgets_str(FILE *file, const char *terminating_string)
67 return xmalloc_fgets_internal(file, terminating_string, 0, NULL);
70 char* FAST_FUNC xmalloc_fgets_str_len(FILE *file, const char *terminating_string, size_t *maxsz_p)
72 return xmalloc_fgets_internal(file, terminating_string, 0, maxsz_p);
75 char* FAST_FUNC xmalloc_fgetline_str(FILE *file, const char *terminating_string)
77 return xmalloc_fgets_internal(file, terminating_string, 1, NULL);