Xref: utzoo comp.lang.c:17074 comp.unix.wizards:15123 Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ames!oliveb!pyramid!athertn!paul From: paul@athertn.Atherton.COM (Paul Sander) Newsgroups: comp.lang.c,comp.unix.wizards Subject: Re: How to predict size of outcome of vsprintf? Summary: Should be possible Keywords: vsprintf formatted conversion Message-ID: <412@athertn.Atherton.COM> Date: 21 Mar 89 03:08:00 GMT References: <993@etnibsd.UUCP> <9872@smoke.BRL.MIL> Organization: Atherton Technology, Sunnyvale, CA Lines: 45 I seem to have missed the original posting, so I'll follow up Doug Gwyn's followup... In article <9872@smoke.BRL.MIL>, gwyn@smoke.BRL.MIL (Doug Gwyn ) writes: > In article <993@etnibsd.UUCP> sean@etnibsd.UUCP (Sean McElroy) writes: > >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? > > No. Sometimes you can accurately predict an upper bound on the output > string length; for example if the format is "%d" and the numerical > argument is known to lie between 0 and 5000, the maximum number of > characters for the *sprintf() output will be 5 (including the null > byte at the end). > > >Any suggestions welcome. > > Don't use *sprintf() when you can't be sure that the output length > will be small enough. Seriously. My guess is that Sean wants to malloc enough space for his output, since he doesn't know how long it is. I like to do that from time to time myself when I have to copy user data (which I have very little control over) into an array of strings that I display later (e.g., in a scrollpane). So far, I've been lucky in that my data are usually displayed in some fixed format, followed by a variable length string. Calculating the length of *sprintf is easy in this case (at least in a platform- and application- dependent way) by summing the ceilings of the lengths of the fixed part of the output, and adding the strlen of the variable length part (plus 1 for the null). It seems to me that it should be possible to write a printf-like function that scans the format string and remaining arguments, returning the ceiling of the length of the result of the *sprintf. I realize that this problem can only be solved on a platform-by-platform basis, but thisseems like a fundamental enough problem that someone somewhere must have done it for some platforms. Has anyone tried? -- Paul Sander (408) 734-9822 | Do YOU get nervous when a paul@Atherton.COM | sys{op,adm,prg,engr} says {decwrl,sun,hplabs!hpda}!athertn!paul | "oops..." ?