Fix compiler warning
[platform/upstream/c-ares.git] / ares__read_line.c
1 /* $Id$ */
2
3 /* Copyright 1998 by the Massachusetts Institute of Technology.
4  *
5  * Permission to use, copy, modify, and distribute this
6  * software and its documentation for any purpose and without
7  * fee is hereby granted, provided that the above copyright
8  * notice appear in all copies and that both that copyright
9  * notice and this permission notice appear in supporting
10  * documentation, and that the name of M.I.T. not be used in
11  * advertising or publicity pertaining to distribution of the
12  * software without specific, written prior permission.
13  * M.I.T. makes no representations about the suitability of
14  * this software for any purpose.  It is provided "as is"
15  * without express or implied warranty.
16  */
17
18 #include "setup.h"
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include "ares.h"
23 #include "ares_private.h"
24
25 /* This is an internal function.  Its contract is to read a line from
26  * a file into a dynamically allocated buffer, zeroing the trailing
27  * newline if there is one.  The calling routine may call
28  * ares__read_line multiple times with the same buf and bufsize
29  * pointers; *buf will be reallocated and *bufsize adjusted as
30  * appropriate.  The initial value of *buf should be NULL.  After the
31  * calling routine is done reading lines, it should free *buf.
32  */
33 int ares__read_line(FILE *fp, char **buf, size_t *bufsize)
34 {
35   char *newbuf;
36   size_t offset = 0;
37   size_t len;
38
39   if (*buf == NULL)
40     {
41       *buf = malloc(128);
42       if (!*buf)
43         return ARES_ENOMEM;
44       *bufsize = 128;
45     }
46
47   while (1)
48     {
49       if (!fgets(*buf + offset, (int)(*bufsize - offset), fp))
50         return (offset != 0) ? 0 : (ferror(fp)) ? ARES_EFILE : ARES_EOF;
51       len = offset + strlen(*buf + offset);
52       if ((*buf)[len - 1] == '\n')
53         {
54           (*buf)[len - 1] = 0;
55           break;
56         }
57       offset = len;
58
59       /* Allocate more space. */
60       newbuf = realloc(*buf, *bufsize * 2);
61       if (!newbuf)
62         return ARES_ENOMEM;
63       *buf = newbuf;
64       *bufsize *= 2;
65     }
66   return ARES_SUCCESS;
67 }