1
2
3
4
5
6
7
8
9
10#include "libbb.h"
11
12static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string, int chop_off, size_t *maxsz_p)
13{
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;
21
22 while (1) {
23 ch = fgetc(file);
24 if (ch == EOF) {
25 if (idx == 0)
26 return linebuf;
27 break;
28 }
29
30 if (idx >= linebufsz) {
31 linebufsz += 200;
32 linebuf = xrealloc(linebuf, linebufsz);
33 if (idx >= maxsz) {
34 linebuf[idx] = ch;
35 idx++;
36 break;
37 }
38 }
39
40 linebuf[idx] = ch;
41 idx++;
42
43
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;
51 }
52 }
53
54 linebuf = xrealloc(linebuf, idx + 1);
55 linebuf[idx] = '\0';
56 *maxsz_p = idx;
57 return linebuf;
58}
59
60
61
62
63
64char* FAST_FUNC xmalloc_fgets_str(FILE *file, const char *terminating_string)
65{
66 size_t maxsz = INT_MAX - 4095;
67 return xmalloc_fgets_internal(file, terminating_string, 0, &maxsz);
68}
69
70char* FAST_FUNC xmalloc_fgets_str_len(FILE *file, const char *terminating_string, size_t *maxsz_p)
71{
72 size_t maxsz;
73
74 if (!maxsz_p) {
75 maxsz = INT_MAX - 4095;
76 maxsz_p = &maxsz;
77 }
78 return xmalloc_fgets_internal(file, terminating_string, 0, maxsz_p);
79}
80
81char* FAST_FUNC xmalloc_fgetline_str(FILE *file, const char *terminating_string)
82{
83 size_t maxsz = INT_MAX - 4095;
84 return xmalloc_fgets_internal(file, terminating_string, 1, &maxsz);
85}
86