Xref: utzoo comp.lang.c:17073 comp.unix.wizards:15121 Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!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: <9979@bloom-beacon.MIT.EDU> Date: 21 Mar 89 04:15:41 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: 47 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 included an excerpt from a that included >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 arbitrarily big.) 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.) Steve Summit scs@adam.pika.mit.edu