Redfoxmoon / cross / slibtool

Forked from cross/slibtool 11 months ago
Clone

Blame src/internal/slibtool_dprintf_impl.c

139ca7
/*******************************************************************/
139ca7
/*  slibtool: a skinny libtool implementation, written in C        */
139ca7
/*  Copyright (C) 2016--2018  Z. Gilboa                            */
139ca7
/*  Released under the Standard MIT License; see COPYING.SLIBTOOL. */
139ca7
/*******************************************************************/
139ca7
5cc5f5
#include <stdio.h>
5cc5f5
#include <stdarg.h>
5cc5f5
#include <stdlib.h>
5cc5f5
#include <unistd.h>
5cc5f5
#include <errno.h>
5cc5f5
5cc5f5
int slbt_dprintf(int fd, const char * fmt, ...)
5cc5f5
{
5cc5f5
	int	ret;
5cc5f5
	int	cnt;
5cc5f5
	int	size;
5cc5f5
	va_list	ap;
5cc5f5
	char *	ch;
5cc5f5
	char *	buf;
5cc5f5
	char	chbuf[2048];
5cc5f5
5cc5f5
	va_start(ap,fmt);
5cc5f5
5cc5f5
	size = sizeof(chbuf);
5cc5f5
	buf  = ((cnt = vsnprintf(chbuf,size,fmt,ap)) < size)
5cc5f5
		? chbuf : malloc(cnt + 1);
5cc5f5
5cc5f5
	va_end(ap);
5cc5f5
5cc5f5
	if (buf == chbuf) {
5cc5f5
		(void)0;
5cc5f5
5cc5f5
	} else if (buf) {
5cc5f5
		va_start(ap,fmt);
5cc5f5
		vsprintf(buf,fmt,ap);
5cc5f5
		va_end(ap);
5cc5f5
5cc5f5
	} else {
5cc5f5
		return -1;
5cc5f5
	}
5cc5f5
5cc5f5
	ret = 0;
5cc5f5
	ch  = buf;
5cc5f5
5cc5f5
	for (; cnt && ret>=0; ) {
5cc5f5
		ret = write(fd,ch,cnt);
5cc5f5
5cc5f5
		while ((ret < 0) && (errno == EINTR))
5cc5f5
			ret = write(fd,ch,cnt);
5cc5f5
5cc5f5
		ch  += ret;
5cc5f5
		cnt -= ret;
5cc5f5
	}
5cc5f5
5cc5f5
	ret = (ret < 0) ? -1 : ch - buf;
5cc5f5
5cc5f5
	if (buf != chbuf)
5cc5f5
		free(buf);
5cc5f5
5cc5f5
	return ret;
5cc5f5
}