I've been looking for a better version of snprintf() to include in
the nmh distribution, but haven't found one yet.
I wasn't on nmh-workers in May, so I didn't see that one... is this
any better?
/*
* Portable working snprintf().
* Created by Sal Valente <svalente(_at_)mit(_dot_)edu> 11/29/97
* Public domain.
*
* Wow, this is a bad idea.
* snprintf() should be implemented as part of stdio, not on top of it.
* Oh well, at least this works and it's secure.
*
* Idea: Write all the data into a pipe, then read as much as can
* fit from the pipe into the buffer.
*
* Who ever used pipe() without fork() before?
*/
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
int snprintf (char *buf, int size, char *format, ...)
{
va_list ap;
int fildes[2], status, len;
FILE *fp;
status = pipe (fildes);
if (status < 0)
return (status);
fp = fdopen (fildes[1], "w");
if (fp == NULL) {
close (fildes[0]);
close (fildes[1]);
return (-1);
}
va_start (ap, format);
vfprintf (fp, format, ap);
va_end (ap);
fclose (fp);
size--;
len = 0;
while (len < size) {
status = read (fildes[0], buf+len, size-len);
if (status <= 0)
break;
len += status;
}
buf[len] = 0;
close (fildes[0]);
return (status < 0 ? status : len);
}