How to predict size of outcome of vsprintf?
Miles Bader
bader+ at andrew.cmu.edu
Wed Mar 22 14:29:07 AEST 1989
bzs at 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
More information about the Comp.unix.wizards
mailing list