/* * snprintf() quicky using temporary files. * Not stress tested, but it seems to work. * * Returns the number of bytes that would have been output by printf. * Does not check whether a negative value if passed in for n (as it's unsigned); * some implementations cast n to int and than compare with 0. * * Casper Dik (Casper.Dik@Holland.Sun.COM) */ #include #include #include int snprintf(char * buf, size_t n, const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = vsnprintf(buf, n, fmt, ap); va_end(ap); return ret; } static char template[] = "/tmp/snprintfXXXXXX"; int vsnprintf(char *buf, size_t n, const char *fmt, va_list ap) { char templ[sizeof(template)]; int s; int ret, cnt = 0, nread; FILE *fp; strcpy(templ,template); s = mkstemp(templ); if (s < 0) return -1; (void) unlink(templ); fp = fdopen(s, "w+"); if (fp == NULL) { close(s); return -1; } ret = vfprintf(fp, fmt, ap); if (ret < 0 || fseek(fp, 0, SEEK_SET) < 0) { fclose(fp); return -1; } while (cnt < n && (nread = fread(buf + cnt, 1, n - cnt, fp)) > 0) cnt += nread; buf[cnt-1] = '\0'; /* cnt is atmost n */ fclose(fp); return ret; }