sprintf return value

Chris Torek chris at mimsy.UUCP
Thu May 12 14:26:48 AEST 1988


In article <2855 at phoenix.Princeton.EDU> lgy at pupthy2.PRINCETON.EDU
(Larry Yaffe) asks in an aside:
>Does anyone know why the folks at Berkeley chose to have their
>sprintf return its first argument, instead of the number of characters
>printed?

Because it had been that way since 32V.  Indeed, the 4.3BSD <stdio.h>
noted

	char *sprintf();	/* too painful to do right */

where `right' presumably meant

	int sprintf();

(or, in New C, `int sprintf(char *str, const char *fmt, ...);'.)

This has been fixed since then; we (read: Keith Bostic) went through
all the utilities and got rid of assumptions about sprintf()'s return
value.  (Actually, I am not sure anyone has gone through /usr/src/new
yet.)  If you want to fix this in older BSD distributions, here is
a functioning, though machine dependent, sprintf and vsprintf.  (Compile
everything but isprintf() below with `-Dsprintf=isprintf'.)

	#include <stdio.h>

	int
	isprintf(s, fmt, args)
		char *s, *fmt;
	{
		FILE f;
		int ret;

		f._flag = _IOSTRG;	/* _IOWRT tickles bug in flsbuf */
		f._ptr = s;
		f._cnt = 32767;		/* `infinity' */
		ret = _doprnt(fmt, &args, &f);
		*f._ptr = 0;
		return (ret);
	}

and

	#include <stdio.h>
	#include <varargs.h>

	int
	vsprintf(s, fmt, ap)
		char *s, *fmt;
		va_list ap;
	{
		FILE f;
		int ret;

		f._flag = _IOSTRG;	/* _IOWRT tickles bug in flsbuf */
		f._ptr = s;
		f._cnt = 32767;		/* `infinity' */
		ret = _doprnt(fmt, ap, &f);
		*f._ptr = 0;
		return (ret);
	}
-- 
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.unix.wizards mailing list