Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!pasteur!ames!ncar!boulder!sunybcs!bingvaxu!leah!rpi!batcomputer!cornell!rochester!pt.cs.cmu.edu!andrew.cmu.edu!bader+ From: bader+@andrew.cmu.edu (Miles Bader) Newsgroups: comp.unix.wizards,comp.lang.c Subject: Re: How to predict size of outcome of vsprintf? Message-ID: Date: 22 Mar 89 04:29:07 GMT References: <993@etnibsd.UUCP> <9872@smoke.BRL.MIL> <28831@bu-cs.BU.EDU> <1618@thor.acc.stolaf.edu> <9979@bloom-beacon.MIT.EDU>, <28874@bu-cs.BU.EDU> Organization: Information Technology Center, Carnegie Mellon, Pittsburgh, PA Lines: 59 In-Reply-To: <28874@bu-cs.BU.EDU> Xref: utzoo comp.unix.wizards:15142 comp.lang.c:17100 bzs@bu-cs.BU.EDU (Barry Shein) writes: > Ok, there are two thoughts here: > > 1. How to find out the number of characters a printf > operation will generate. > > 2. How to limit a printf operation to a buffer size. > > I suggested the first might be the result of printing to a null > pointer (buffer or file.) What I'd really like would be a new function that could act as a basis for all the other printf functions, and make it possible to emulate them in nice ways. I would make it a varargs function that takes a bounded output buffer and is restartable at the point where it stops due to running into the end of the buffer. E.g. (pardon the name, but I can't think of a better one): /* fmtP and valP are modified so that re-calling the function * will start formatting where it left off */ int rvsnprintf(buf,maxlen,fmtP,valP) char *buf; int maxlen; char **fmtP; /* in/out */ va_list *valP; /* in/out */ vsprintf, vfprintf, etc, are all trivially derivable from this (as is the one someone mentioned a while ago that returned a realloced buffer). Say I write my own buffered io package; I can just call rvsnprintf like: streamvprintf(stream,fmt,val) STREAM *stream; char *fmt; va_list val; { ... while(*fmt!='\0){ int written=rvsnprintf(stream->pos,stream->left,&fmt,&val); if(*fmt!='\0') /* ran out of space */ streamflush(stream); else{ stream->pos+=written; stream->left-=written; } } ... } None of the other proposals I've seen give you this capability (or do it expensively, like mallocing the buffer), and I can't see how it would be much more difficult to implement than existing printfs... -Miles