aboutsummaryrefslogtreecommitdiff
path: root/utility.c
diff options
context:
space:
mode:
Diffstat (limited to 'utility.c')
-rw-r--r--utility.c75
1 files changed, 27 insertions, 48 deletions
diff --git a/utility.c b/utility.c
index a45edde5d..de53dbda8 100644
--- a/utility.c
+++ b/utility.c
@@ -1586,56 +1586,35 @@ extern int find_real_root_device_name(char* name)
1586} 1586}
1587#endif 1587#endif
1588 1588
1589const unsigned int CSTRING_BUFFER_LENGTH = 1024; 1589static const int GROWBY = 80; /* how large we will grow strings by */
1590/* recursive parser that returns cstrings of arbitrary length
1591 * from a FILE*
1592 */
1593static char *
1594cstring_alloc(FILE* f, int depth)
1595{
1596 char *cstring;
1597 char buffer[CSTRING_BUFFER_LENGTH];
1598 int target = CSTRING_BUFFER_LENGTH * depth;
1599 int c, i, len, size;
1600
1601 /* fill buffer */
1602 i = 0;
1603 while ((c = fgetc(f)) != EOF) {
1604 buffer[i] = (char) c;
1605 if (buffer[i++] == 0x0a) { break; }
1606 if (i == CSTRING_BUFFER_LENGTH) { break; }
1607 }
1608 len = i;
1609
1610 /* recurse or malloc? */
1611 if (len == CSTRING_BUFFER_LENGTH) {
1612 cstring = cstring_alloc(f, (depth + 1));
1613 } else {
1614 /* [special case] EOF */
1615 if ((depth | len) == 0) { return NULL; }
1616
1617 /* malloc */
1618 size = target + len + 1;
1619 cstring = malloc(size);
1620 if (!cstring) { return NULL; }
1621 cstring[size - 1] = 0;
1622 }
1623
1624 /* copy buffer */
1625 if (cstring) {
1626 memcpy(&cstring[target], buffer, len);
1627 }
1628 return cstring;
1629}
1630 1590
1631/* 1591/* get_line_from_file() - This function reads an entire line from a text file
1632 * wrapper around recursive cstring_alloc 1592 * up to a newline. It returns a malloc'ed char * which must be stored and
1633 * it's the caller's responsibility to free the cstring 1593 * free'ed by the caller. */
1634 */ 1594extern char *get_line_from_file(FILE *file)
1635char *
1636cstring_lineFromFile(FILE *f)
1637{ 1595{
1638 return cstring_alloc(f, 0); 1596 int ch;
1597 int idx = 0;
1598 char *linebuf = NULL;
1599 int linebufsz = 0;
1600
1601 while (1) {
1602 ch = fgetc(file);
1603 if (ch == EOF)
1604 break;
1605 /* grow the line buffer as necessary */
1606 if (idx > linebufsz-1)
1607 linebuf = realloc(linebuf, linebufsz += GROWBY);
1608 linebuf[idx++] = (char)ch;
1609 if ((char)ch == '\n')
1610 break;
1611 }
1612
1613 if (idx == 0)
1614 return NULL;
1615
1616 linebuf[idx] = 0;
1617 return linebuf;
1639} 1618}
1640 1619
1641/* END CODE */ 1620/* END CODE */