mprintf.c 1.22 KB
Newer Older
1 2 3 4
#include <config.h>

#include <stdio.h>
#include <stdarg.h>
5 6 7
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
8 9 10 11 12 13

#include "mprintf.h"

// TODO: check for asprintf in configure and
// write a replacement for such situations.

14
char * mprintf(const char *fmt, ...) {
15 16 17 18
	char *p;
	int r;
	va_list va;

19 20
	va_start(va, fmt);
	r = vasprintf(&p, fmt, va);
21
	va_end(va);
Bernhard Link's avatar
Bernhard Link committed
22
	/* return NULL both when r is < 0 and when NULL was returned */
23
	if (r < 0)
24 25 26 27 28
		return NULL;
	else
		return p;
}

29
char * vmprintf(const char *fmt, va_list va) {
30 31 32
	char *p;
	int r;

33
	r = vasprintf(&p, fmt, va);
Bernhard Link's avatar
Bernhard Link committed
34
	/* return NULL both when r is < 0 and when NULL was returned */
35
	if (r < 0)
36 37 38 39
		return NULL;
	else
		return p;
}
40 41 42 43 44 45 46 47 48 49 50

#ifndef HAVE_DPRINTF
int dprintf(int fd, const char *format, ...){
	char *buffer;
	int ret;

	va_list va;

	va_start(va, format);
	buffer = vmprintf(format, va);
	va_end(va);
51
	if (buffer == NULL)
52 53 54 55 56 57 58 59 60 61
		return -1;
	ret = write(fd, buffer, strlen(buffer));
	free(buffer);
	return ret;
}
#endif

#ifndef HAVE_STRNDUP
/* That's not the best possible strndup implementation, but it suffices for what
 * it is used here */
62
char *strndup(const char *str, size_t n) {
63
	char *r = malloc(n+1);
64
	if (r == NULL)
65
		return r;
66
	memcpy(r, str, n);
67 68 69 70
	r[n] = '\0';
	return r;
}
#endif