thomas@utah-gr.UUCP (Spencer W. Thomas) (02/10/84)
My solution to "gee, I wish printf had a format to...." was to implement a "%p" format which calls an arbitrary procedure to format the data. It was about 6 lines of code added to printf. The formatting procedure can even call printf recursively! (4.x bsd, anyway). It would then be trivial to add a "print error message" formatter. Here is the message I sent out locally describing it. Code available on request for (at least) 4.xBSD, as a diff listing against the distributed doprnt.s. >Date: 10 Mar 1983 15:55-MST >From: Spencer W. Thomas <thomas> >Subject: New printf format (feep) >To: vax-general A new format effector has been added to printf. The %p format can be used to format an argument using an arbitrary procedure (thus p). The %p format takes TWO arguments - the first is the address of the procedure to call, the second is the data item. The procedure is called as shown: proc( fdesc, arg, flags, width, ndigits ) FILE *fdesc; char *arg; int flags, width, ndigits; fdesc is the FILE which is being written to. arg is a pointer to the item in the printf argument list. flags is a bit mask describing the presence of various options between the `%' and the `p'. The bits are: 0x01 width was specified. The number is passed in width. 0x02 ndigits was specified. The number is passed in ndigits. 0x04 width was specified with a leading 0. 0x08 a minus sign was included. 0x10 a plus sign was included. 0x20 a # was included. 0x40 a capital `P' was used rather than a lower case `p'. 0x80 a space was included. The printf specification may include numbers between the % and the p, separated by a `.'. The first is passed in the variable width, the second in ndigits. These arguments should be ignored if the appropriate flag bit is not set. The formatting function must return the number of bytes used from the printf argument list (i.e. when formatting an int, return sizeof(int), when formatting a double or float, return sizeof(double), when formatting a pointer, return sizeof(pointer). The formatting function may call printf recursively. A sample function which formats a point is given below, along with a sample call. struct point { float xyz[3]; } p; /* Format a point as [x y z] using `g' format. Ignore flags, etc. */ prpoint( f, pt, flags, wid, nd ) FILE *f; point *pt; { fprintf(f, "[%g %g %g]", pt->xyz[0], pt->xyz[1], pt->xyz[2]); return sizeof(point); } /* * A sample call. Note that the actual point is put in the * arguments, NOT a pointer. printf("p value = %p\n", prpoint, p);