How about a `gprintf' for Turbo C

Chris Torek chris at mimsy.UUCP
Thu Apr 21 08:34:51 AEST 1988


In article <4576 at cup.portal.com> Devin_E_Ben-Hur at cup.portal.com writes:
>int gprintf(char *format, ...) {
>  char buf[81];
   ...
>  ret = vsprintf(buf,format,args);
>  outtext(buf);

I thought we just finished arguing over why `sprintf' is evil :-) .
Note that this limits you to printing 80 characters or less.  If
you had a function-style stdio, you could do this:

#include <stdio.h>
#include <stdarg.h>
/* etc */

#define GP_BUFSIZE 80	/* or whatever */

static int gwrite(void *context, const char *buf, int n) {
	char *realbuf = (char *)context;
	int k, left = n;

	while (left > 0) {
		k = left > GP_BUFSIZE ? GP_BUFSIZE : left;
		(void) memmove((void *)realbuf, (void *)buf, k);
		realbuf[k] = 0;
		outtext(realbuf);
		buf += k;
		left -= k;
	}
	return (n);
}

int gprintf(char *fmt, ...) {
	FILE *fp;
	va_list ap;
	int rv;
	char buf[GP_BUFSIZE + 1];	/* leave room for '\0'! */

	if ((fp = fwopen((void *)buf, gwrite)) == NULL)
		return (-1);
	va_start(ap, fmt);
	rv = vfprintf(fp, fmt, ap);
	va_end(ap);
	(void) fclose(fp);
	return (rv);
}

A bit clumsy, I admit, but this has no output restrictions.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list