xref: /freebsd/contrib/sendmail/libsm/stringf.c (revision f0adf7f5cdd241db2f2c817683191a6ef64a4e95)
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 #include <sm/gen.h>
11 SM_RCSID("@(#)$Id: stringf.c,v 1.15 2001/09/11 04:04:49 gshapiro Exp $")
12 #include <errno.h>
13 #include <stdio.h>
14 #include <sm/exc.h>
15 #include <sm/heap.h>
16 #include <sm/string.h>
17 #include <sm/varargs.h>
18 
19 /*
20 **  SM_STRINGF_X -- printf() to dynamically allocated string.
21 **
22 **	Takes the same arguments as printf.
23 **	It returns a pointer to a dynamically allocated string
24 **	containing the text that printf would print to standard output.
25 **	It raises an exception on error.
26 **	The name comes from a PWB Unix function called stringf.
27 **
28 **	Parameters:
29 **		fmt -- format string.
30 **		... -- arguments for format.
31 **
32 **	Returns:
33 **		Pointer to a dynamically allocated string.
34 **
35 **	Exceptions:
36 **		F:sm_heap -- out of memory (via sm_vstringf_x()).
37 */
38 
39 char *
40 #if SM_VA_STD
41 sm_stringf_x(const char *fmt, ...)
42 #else /* SM_VA_STD */
43 sm_stringf_x(fmt, va_alist)
44 	const char *fmt;
45 	va_dcl
46 #endif /* SM_VA_STD */
47 {
48 	SM_VA_LOCAL_DECL
49 	char *s;
50 
51 	SM_VA_START(ap, fmt);
52 	s = sm_vstringf_x(fmt, ap);
53 	SM_VA_END(ap);
54 	return s;
55 }
56 
57 /*
58 **  SM_VSTRINGF_X -- printf() to dynamically allocated string.
59 **
60 **	Parameters:
61 **		fmt -- format string.
62 **		ap -- arguments for format.
63 **
64 **	Returns:
65 **		Pointer to a dynamically allocated string.
66 **
67 **	Exceptions:
68 **		F:sm_heap -- out of memory
69 */
70 
71 char *
72 sm_vstringf_x(fmt, ap)
73 	const char *fmt;
74 	SM_VA_LOCAL_DECL
75 {
76 	char *s;
77 
78 	sm_vasprintf(&s, fmt, ap);
79 	if (s == NULL)
80 	{
81 		if (errno == ENOMEM)
82 			sm_exc_raise_x(&SmHeapOutOfMemory);
83 		sm_exc_raisenew_x(&SmEtypeOs, errno, "sm_vasprintf", NULL);
84 	}
85 	return s;
86 }
87