update from main archive 961113
[glibc.git] / stdio / vasprintf.c
blobd2ad6b1da6b047b67bfe8ba0aec43e50df296119
1 /* Copyright (C) 1991, 1992 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
14 You should have received a copy of the GNU Library General Public
15 License along with the GNU C Library; see the file COPYING.LIB. If
16 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
17 Cambridge, MA 02139, USA. */
19 #include <ansidecl.h>
20 #include <stddef.h>
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
28 /* Enlarge STREAM's buffer. */
29 static void
30 DEFUN(enlarge_buffer, (stream, c),
31 register FILE *stream AND int c)
33 ptrdiff_t bufp_offset = stream->__bufp - stream->__buffer;
34 char *newbuf;
36 stream->__bufsize += 100;
37 newbuf = (char *) realloc ((PTR) stream->__buffer, stream->__bufsize);
38 if (newbuf == NULL)
40 free ((PTR) stream->__buffer);
41 stream->__buffer = stream->__bufp
42 = stream->__put_limit = stream->__get_limit = NULL;
43 stream->__error = 1;
45 else
47 stream->__buffer = newbuf;
48 stream->__bufp = stream->__buffer + bufp_offset;
49 stream->__get_limit = stream->__put_limit;
50 stream->__put_limit = stream->__buffer + stream->__bufsize;
51 if (c != EOF)
52 *stream->__bufp++ = (unsigned char) c;
56 /* Write formatted output from FORMAT to a string which is
57 allocated with malloc and stored in *STRING_PTR. */
58 int
59 DEFUN(vasprintf, (string_ptr, format, args),
60 char **string_ptr AND CONST char *format AND va_list args)
62 FILE f;
63 int done;
65 memset ((PTR) &f, 0, sizeof (f));
66 f.__magic = _IOMAGIC;
67 f.__bufsize = 100;
68 f.__buffer = (char *) malloc (f.__bufsize);
69 if (f.__buffer == NULL)
70 return -1;
71 f.__bufp = f.__buffer;
72 f.__put_limit = f.__buffer + f.__bufsize;
73 f.__mode.__write = 1;
74 f.__room_funcs.__output = enlarge_buffer;
75 f.__seen = 1;
77 done = vfprintf (&f, format, args);
78 if (done < 0)
79 return done;
81 *string_ptr = realloc (f.__buffer, (f.__bufp - f.__buffer) + 1);
82 if (*string_ptr == NULL)
83 *string_ptr = f.__buffer;
84 (*string_ptr)[f.__bufp - f.__buffer] = '\0';
85 return done;