Subject: Re: printf formats again
To: David Weaver <>
From: Don Lewis <>
List: current-users
Date: 11/17/1996 18:23:28
On Nov 14,  9:10am, David Weaver wrote:
} Subject: Re: printf formats again
} So, why not let the data convert itself?  Of course, this isn't easy in C
} which does not support encapsulation and methods and such.  Still it can
} be done.  How about declaring a conversion method for each opaque type in
} the system?  It would be the responsibility of the creator of the type to
} create the method in the same scope as the type.  For example, following
} the declaration of off_t could be a function of the form
}   char *off_t_to_string(off_t p);
} To print the type, you would simply use something like:
}   off_t p;
}   /* p = whatever; */
}   printf("Offset is %s\n", off_t_to_string(p));

This is the most portable in that it could handle any type, integral,
composite, or whatever.  You would still need to pass another parameter
to the conversion function to specify the precise formatting, which puts
the formatting in two different places.

The problems with this scheme are:
	If the conversion function returns a pointer to a static buffer,
	then you can only use it once per printf().

	If the conversion function returns a pointer to a malloc()'d
	buffer, you need to arrange to free() it, or you'll have a
	core leak.

	You can solve both of the above by passing in a pointer to
	an external buffer.

	There's an extra data copy if you care about efficiency.

	How do you do the corresponding scanf() implementation.

Also don't forget about syslog() and the ugly stuff it has to do to
implement %m.

There's lots of userland code around that does printf() types of things
with custom % types that copy various things into the output stream (and
may not eat an argument).  It would be nice if they didn't have to duplicate
all the complexity of printf().

The more I think about it, the more I like the idea of an extensible
printf(), probably an extended printf() function that is passed a
pointer to a table of methods.

			---  Truck