How to predict size of outcome of vsprintf?

Miles Bader bader+ at andrew.cmu.edu
Wed Mar 22 15:07:31 AEST 1989


[Why do problems with my messages always become evident 10 seconds
 AFTER I send them?]

Miles Bader <bader+ at andrew.cmu.edu> writes:
>     /* 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 */

Oops, you need one more variable, since sometimes a directive (%s,
etc) can be too large for the buffer, so now:

    /* fmtP, valP and offsP are modified so that re-calling the function
     * will start formatting where it left off
     */
    int rvsnprintf(buf,maxlen,fmtP,valP,offsP)
    char *buf;
    int maxlen;
    char **fmtP;        /* in/out */
    va_list *valP;      /* in/out */
    int *offsP;		/* in/out */

*offsP says how many characters to drop before putting stuff into the
buffer, and should initially be 0.  With this change, it should work
correctly for any size output buffer (even small ones).

>     {
>         ...
>         while(*fmt!='\0){
>             int written=rvsnprintf(stream->pos,stream->left,&fmt,&val);

Becomes:

    {
	int offs=0;
        ...
        while(*fmt!='\0){
            int written=rvsnprintf(stream->pos,stream->left,&fmt,&val,&offs);

-Miles



More information about the Comp.unix.wizards mailing list