summaryrefslogtreecommitdiff
path: root/src/internal/tpax_dprintf_impl.c
blob: b8d2b0b97ef58eb5caff933693ac3a79e4b61371 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**************************************************************/
/*  tpax: a topological pax implementation                    */
/*  Copyright (C) 2020--2021  SysDeer Technologies, LLC       */
/*  Released under GPLv2 and GPLv3; see COPYING.TPAX.         */
/**************************************************************/

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int tpax_dprintf(int fd, const char * fmt, ...)
{
	int	ret;
	int	cnt;
	int	size;
	va_list	ap;
	char *	ch;
	char *	buf;
	char	chbuf[2048];

	va_start(ap,fmt);

	size = sizeof(chbuf);
	buf  = ((cnt = vsnprintf(chbuf,size,fmt,ap)) < size)
		? chbuf : malloc(cnt + 1);

	va_end(ap);

	if (buf == chbuf) {
		(void)0;

	} else if (buf) {
		va_start(ap,fmt);
		vsprintf(buf,fmt,ap);
		va_end(ap);

	} else {
		return -1;
	}

	ret = 0;
	ch  = buf;

	for (; cnt && ret>=0; ) {
		ret = write(fd,ch,cnt);

		while ((ret < 0) && (errno == EINTR))
			ret = write(fd,ch,cnt);

		ch  += ret;
		cnt -= ret;
	}

	ret = (ret < 0) ? -1 : ch - buf;

	if (buf != chbuf)
		free(buf);

	return ret;
}