blob: 1bc6c3b1c0cb89b01a3008af4209f735fd3ac321 [file] [log] [blame]
Eric Andersenbdfd0d72001-10-24 05:00:29 +00001/* vi: set sw=4 ts=4: */
Glenn L McGrath17822cd2001-06-13 07:34:03 +00002/*
Eric Andersenbdfd0d72001-10-24 05:00:29 +00003 * Utility routines.
Glenn L McGrath17822cd2001-06-13 07:34:03 +00004 *
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005 * Copyright (C) many different people.
Eric Andersencb81e642003-07-14 21:21:08 +00006 * If you wrote this, please acknowledge your work.
Glenn L McGrath17822cd2001-06-13 07:34:03 +00007 *
"Robert P. J. Day"5d8843e2006-07-10 11:41:19 +00008 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
Glenn L McGrath17822cd2001-06-13 07:34:03 +00009 */
10
Matt Kraaibcca3312001-10-18 17:04:22 +000011#include "libbb.h"
12
13/* Read up to (and including) TERMINATING_STRING from FILE and return it.
14 * Return NULL on EOF. */
Glenn L McGrath17822cd2001-06-13 07:34:03 +000015
Denis Vlasenkoddec5af2006-10-26 23:25:17 +000016char *xmalloc_fgets_str(FILE *file, const char *terminating_string)
Glenn L McGrath17822cd2001-06-13 07:34:03 +000017{
18 char *linebuf = NULL;
19 const int term_length = strlen(terminating_string);
20 int end_string_offset;
21 int linebufsz = 0;
22 int idx = 0;
23 int ch;
24
25 while (1) {
26 ch = fgetc(file);
27 if (ch == EOF) {
Matt Kraaibcca3312001-10-18 17:04:22 +000028 free(linebuf);
29 return NULL;
Glenn L McGrath17822cd2001-06-13 07:34:03 +000030 }
31
32 /* grow the line buffer as necessary */
33 while (idx > linebufsz - 2) {
Denis Vlasenkoddec5af2006-10-26 23:25:17 +000034 linebufsz += 200;
35 linebuf = xrealloc(linebuf, linebufsz);
Glenn L McGrath17822cd2001-06-13 07:34:03 +000036 }
37
38 linebuf[idx] = ch;
39 idx++;
40
41 /* Check for terminating string */
42 end_string_offset = idx - term_length;
Denis Vlasenkoa6dbb082006-10-12 19:29:44 +000043 if (end_string_offset > 0
44 && memcmp(&linebuf[end_string_offset], terminating_string, term_length) == 0
45 ) {
Glenn L McGrath17822cd2001-06-13 07:34:03 +000046 idx -= term_length;
47 break;
48 }
49 }
Denis Vlasenkoa6dbb082006-10-12 19:29:44 +000050 linebuf = xrealloc(linebuf, idx + 1);
Glenn L McGrath17822cd2001-06-13 07:34:03 +000051 linebuf[idx] = '\0';
Denis Vlasenkoa6dbb082006-10-12 19:29:44 +000052 return linebuf;
Glenn L McGrath17822cd2001-06-13 07:34:03 +000053}