Xref: utzoo comp.lang.c:17080 comp.unix.wizards:15127 Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ncar!gatech!bloom-beacon!adam.pika.mit.edu!scs From: scs@adam.pika.mit.edu (Steve Summit) Newsgroups: comp.lang.c,comp.unix.wizards Subject: Re: How to predict size of outcome of vsprintf? Keywords: vsprintf formatted conversion Message-ID: <9985@bloom-beacon.MIT.EDU> Date: 21 Mar 89 05:23:23 GMT References: <993@etnibsd.UUCP> <9872@smoke.BRL.MIL> <28831@bu-cs.BU.EDU> <1618@thor.acc.stolaf.edu> Sender: daemon@bloom-beacon.MIT.EDU Reply-To: scs@adam.pika.mit.edu (Steve Summit) Lines: 52 [Apologies if you see this twice; is there a known problem with canceling cross-posted articles under nntp?] In article <28831@bu-cs.BU.EDU> bzs@bu-cs.BU.EDU (Barry Shein) writes: >Another way to say that is: > print_width = LOGx(N) + 1 >where x (the log base) is the base to be printed in... An occasionally-useful observation is that an upper bound on this value is something like 8*sizeof(int), which is the number of characters it could take to print an int in base 2 (some printf's even provide %b for this purpose!). As Barry noted, this helps only in the simplest cases. (I use it internally to my own version of printf, for the buffer size in which integer conversion, before padding, is performed. Unfortunately, the assumption that sizeof deals in 8-bit units is not perfectly valid.) In article <1618@thor.acc.stolaf.edu> mike@stolaf.edu writes: >The (unreleased) GNU C library contains routines something like: > int snprintf(char *str, size_t len, const char *fmt, ...); > int vsnprintf(char *str, size_t len, const char *fmt, va_list ap); >that do bounds checking on their output. >I also recall a posting by Chris Torek a few >months ago that [mentioned] a routine that looked something like: > FILE *fmemopen(void *mem, size_t len, const char *how); >This solves the same problem, and offers additional advantages as well. My own soon-to-be-released stdio replacement contains char *smprintf(char *fmt, ...) which returns a malloc'ed pointer to an area of memory just big enough for the formatted string. (snprintf only allows you to prevent overflow of a finite-sized buffer; smprintf lets the resultant buffer be as big as it needs to be.) I may also add FILE *strmopen(); char *strmclose(FILE *); which would give you a fd on which you could do arbitrary stdio output, dynamically allocating (and reallocating as needed) an in-memory buffer, the eventual pointer to which would be returned by strmclose. (I've got to think of better names for these; the 'm' is supposed to stand for "malloc" but the overall effect ends up sounding like "stream" which is misleading.) [Exercise for the student: implement smprintf in terms of strmopen, vfprintf, and strmclose.] Steve Summit scs@adam.pika.mit.edu