blob: 41370d1763591b1a29f8462417a096dd6b28553a [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
11
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15
Matt Kraaibcca3312001-10-18 17:04:22 +000016#include "libbb.h"
17
18/* Read up to (and including) TERMINATING_STRING from FILE and return it.
19 * Return NULL on EOF. */
Glenn L McGrath17822cd2001-06-13 07:34:03 +000020
21char *fgets_str(FILE *file, const char *terminating_string)
22{
23 char *linebuf = NULL;
24 const int term_length = strlen(terminating_string);
25 int end_string_offset;
26 int linebufsz = 0;
27 int idx = 0;
28 int ch;
29
30 while (1) {
31 ch = fgetc(file);
32 if (ch == EOF) {
Matt Kraaibcca3312001-10-18 17:04:22 +000033 free(linebuf);
34 return NULL;
Glenn L McGrath17822cd2001-06-13 07:34:03 +000035 }
36
37 /* grow the line buffer as necessary */
38 while (idx > linebufsz - 2) {
Matt Kraaibcca3312001-10-18 17:04:22 +000039 linebuf = xrealloc(linebuf, linebufsz += 1000);
Glenn L McGrath17822cd2001-06-13 07:34:03 +000040 }
41
42 linebuf[idx] = ch;
43 idx++;
44
45 /* Check for terminating string */
46 end_string_offset = idx - term_length;
Denis Vlasenkoa6dbb082006-10-12 19:29:44 +000047 if (end_string_offset > 0
48 && memcmp(&linebuf[end_string_offset], terminating_string, term_length) == 0
49 ) {
Glenn L McGrath17822cd2001-06-13 07:34:03 +000050 idx -= term_length;
51 break;
52 }
53 }
Denis Vlasenkoa6dbb082006-10-12 19:29:44 +000054 linebuf = xrealloc(linebuf, idx + 1);
Glenn L McGrath17822cd2001-06-13 07:34:03 +000055 linebuf[idx] = '\0';
Denis Vlasenkoa6dbb082006-10-12 19:29:44 +000056 return linebuf;
Glenn L McGrath17822cd2001-06-13 07:34:03 +000057}