1 /*
2  * Copyright (c) 2000-2001 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
4  *
5  * By using this file, you agree to the terms and conditions set
6  * forth in the LICENSE file which can be found at the top level of
7  * the sendmail distribution.
8  */
9 
10 #pragma ident	"%Z%%M%	%I%	%E% SMI"
11 
12 #include <sm/gen.h>
13 SM_RCSID("@(#)$Id: stringf.c,v 1.13 2001/03/03 03:40:43 ca Exp $")
14 #include <errno.h>
15 #include <stdio.h>
16 #include <sm/exc.h>
17 #include <sm/heap.h>
18 #include <sm/string.h>
19 #include <sm/varargs.h>
20 
21 /*
22 **  SM_STRINGF_X -- printf() to dynamically allocated string.
23 **
24 **	Takes the same arguments as printf.
25 **	It returns a pointer to a dynamically allocated string
26 **	containing the text that printf would print to standard output.
27 **	It raises an exception on error.
28 **	The name comes from a PWB Unix function called stringf.
29 **
30 **	Parameters:
31 **		fmt -- format string.
32 **		... -- arguments for format.
33 **
34 **	Returns:
35 **		Pointer to a dynamically allocated string.
36 **
37 **	Exceptions:
38 **		F:sm_heap -- out of memory (via sm_vstringf_x()).
39 */
40 
41 char *
42 #if SM_VA_STD
43 sm_stringf_x(const char *fmt, ...)
44 #else /* SM_VA_STD */
45 sm_stringf_x(fmt, va_alist)
46 	const char *fmt;
47 	va_dcl
48 #endif /* SM_VA_STD */
49 {
50 	SM_VA_LOCAL_DECL
51 	char *s;
52 
53 	SM_VA_START(ap, fmt);
54 	s = sm_vstringf_x(fmt, ap);
55 	SM_VA_END(ap);
56 	return s;
57 }
58 
59 /*
60 **  SM_VSTRINGF_X -- printf() to dynamically allocated string.
61 **
62 **	Parameters:
63 **		fmt -- format string.
64 **		ap -- arguments for format.
65 **
66 **	Returns:
67 **		Pointer to a dynamically allocated string.
68 **
69 **	Exceptions:
70 **		F:sm_heap -- out of memory
71 */
72 
73 char *
74 sm_vstringf_x(fmt, ap)
75 	const char *fmt;
76 	SM_VA_LOCAL_DECL
77 {
78 	char *s;
79 
80 	sm_vasprintf(&s, fmt, ap);
81 	if (s == NULL)
82 	{
83 		if (errno == ENOMEM)
84 			sm_exc_raise_x(&SmHeapOutOfMemory);
85 		sm_exc_raisenew_x(&SmEtypeOs, errno, "sm_vasprintf", NULL);
86 	}
87 	return s;
88 }
89