How to predict size of outcome of vsprintf?

Sean McElroy sean at etnibsd.UUCP
Sat Mar 18 04:27:31 AEST 1989


O.K. Unix/C gurus, since vsprintf requires the user to ensure that there
is enough space in the output string, how does one predict the size of
the output string?  Is there a routine which returns the predicted
length of the output string (effectively preforming the printf conversions)
without actually producing the output string?

First an abridged description of what vsprintf does.  Here's it's
declaration:

	char *vsprintf (s, format, ap)
	char *s, *format;
	va_list ap;

Allow me some hand-waving here and let va_list mean "pointer to an argument
list" (see varargs(3) for more detail).  The first argument, "s", is a pointer
to a suitably sized piece of memory.  It is supposed to be large enough
to hold the result of converting the arguments listed in "ap" by the
specifications listed in "format".  Thus the second argument, "format",
is the format string optionally containing conversion specifications.
Finally, "ap" is a pointer to a list of data items which will supply the
data to be converted and then substituted into the string "s".  The function
returns a pointer to "s".

Here's a more general view of the problem.  You are given a format string
of unknown contents (assume that it is a legitamate format string), and
a list of arguments of unknown type (assume that they correspond appropriately
with the conversion specifications in the format string).  How do you
allocate storage for the output string, "s"?

One suggestion is to reproduce the functionality of vsprintf up to the
point where it outputs a character and replace the output-a-character
functionality with count-the-number-of-characters functionality.

I quess since I don't possess the source to vsprintf, et al, I can't be as
certain of reproducing its functionality.  Also this strikes me as such
a fundamental obstacle that it must already have been conquered by someone.

Any suggestions welcome.
-- 
  ____,.,_..,__.,_.,__     Sean Philip McElroy
   __'..__._,_.__.__.__    Eaton Corp., SED
   _,___`_.'__.__.__.__    108 Cherry Hill Dr., Beverly, MA 01922
  ___`..'_,___.__.__,_     uunet!etnibsd!sean



More information about the Comp.unix.wizards mailing list