#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int write_format(int hd, const char *format, ...) {
char *msg;
va_list arg;
int ret;
/* compute the length of the formatted message */
va_start(arg, format);
ret = vsnprintf(NULL, 0, format, arg);
va_end(arg);
/* allocated an array for the formatted message */
if (ret < 0 || (msg = malloc(ret + 1)) == NULL)
return -1;
/* construct the formatted message */
va_start(arg, ap);
ret = vsnprintf(msg, ret + 1, format, arg);
va_end(arg);
/* send the message using the write system call */
ret = write(hd, msg, ret);
free(msg);
return ret;
}
网友评论