Browse Source

Added [v]asprintf()

tags/v0.9.3
Michael Brown 17 years ago
parent
commit
816c8f3b89
2 changed files with 52 additions and 0 deletions
  1. 47
    0
      src/core/asprintf.c
  2. 5
    0
      src/include/stdio.h

+ 47
- 0
src/core/asprintf.c View File

@@ -0,0 +1,47 @@
1
+#include <stdint.h>
2
+#include <stddef.h>
3
+#include <stdlib.h>
4
+#include <stdio.h>
5
+#include <errno.h>
6
+
7
+/**
8
+ * Write a formatted string to newly allocated memory.
9
+ *
10
+ * @v strp		Pointer to hold allocated string
11
+ * @v fmt		Format string
12
+ * @v args		Arguments corresponding to the format string
13
+ * @ret	len		Length of formatted string
14
+ */
15
+int vasprintf ( char **strp, const char *fmt, va_list args ) {
16
+	size_t len;
17
+	va_list args_tmp;
18
+
19
+	/* Calculate length needed for string */
20
+	va_copy ( args_tmp, args );
21
+	len = ( vsnprintf ( NULL, 0, fmt, args_tmp ) + 1 );
22
+	va_end ( args_tmp );
23
+
24
+	/* Allocate and fill string */
25
+	*strp = malloc ( len );
26
+	if ( ! *strp )
27
+		return -ENOMEM;
28
+	return vsnprintf ( *strp, len, fmt, args );
29
+}
30
+
31
+/**
32
+ * Write a formatted string to newly allocated memory.
33
+ *
34
+ * @v strp		Pointer to hold allocated string
35
+ * @v fmt		Format string
36
+ * @v ...		Arguments corresponding to the format string
37
+ * @ret	len		Length of formatted string
38
+ */
39
+int asprintf ( char **strp, const char *fmt, ... ) {
40
+	va_list args;
41
+	int len;
42
+
43
+	va_start ( args, fmt );
44
+	len = vasprintf ( strp, fmt, args );
45
+	va_end ( args );
46
+	return len;
47
+}

+ 5
- 0
src/include/stdio.h View File

@@ -10,10 +10,15 @@ printf ( const char *fmt, ... );
10 10
 extern int __attribute__ (( format ( printf, 3, 4 ) ))
11 11
 snprintf ( char *buf, size_t size, const char *fmt, ... );
12 12
 
13
+extern int __attribute__ (( format ( printf, 2, 3 ) ))
14
+asprintf ( char **strp, const char *fmt, ... );
15
+
13 16
 extern int vprintf ( const char *fmt, va_list args );
14 17
 
15 18
 extern int vsnprintf ( char *buf, size_t size, const char *fmt, va_list args );
16 19
 
20
+extern int vasprintf ( char **strp, const char *fmt, va_list args );
21
+
17 22
 /**
18 23
  * Write a formatted string to a buffer
19 24
  *

Loading…
Cancel
Save