Guessing buffer size needed for sprintf beforehand

Brandon Allbery allbery at ncoast.UUCP
Thu May 12 07:54:45 AEST 1988


As quoted from <136 at insyte.uucp> by jad at insyte.uucp (Jill Diewald):
+---------------
| One solution is to fprintf into a file opened to be /dev/null.
| This requires two calls to the c print fuctions, one to get the
| size and the second to actually print.  Since the first call
| goes to dev/null it should be faster since it doesn't really
| write anything? (Is this true?  For all UNIXs?).  This won't
| work for VMS though.
+---------------

Close.  fprintf() to a newly-created temporary file, then rewind() it (this
is a stdio function) and getc() out of it and send it wherever.  If you need
the size, get the file size using the OS's current-file-position call before
the rewind().  This is perhaps a bit slower than an in-core buffer, but it's
clean and is limited only by free space on the disk!

When I want to do this, I declare a static 32K buffer; on the other hand, I
rarely print a string of over 200 characters anyway.  If I'm doing it to
a file or the terminal as the ultimate destination and I don't have to munge
the output, I just v?printf() to the destination directly and skip the buffer
entirely.

++Brandon
-- 
	      Brandon S. Allbery, moderator of comp.sources.misc
	{well!hoptoad,uunet!marque,cbosgd,sun!mandrill}!ncoast!allbery
Delphi: ALLBERY						     MCI Mail: BALLBERY



More information about the Comp.unix.questions mailing list