Programming Tips - C/C++: My own custom printf()-like function that accepts a variable number of arguments

Date: 2014sep26 Update: 2026sep29 Language: C/C++ Keywords: snprintf, vsprintf, vprintf, vargs, variadic Q. C/C++: My own custom printf()-like function that accepts a variable number of arguments A. Use the va_* family of functions. Full Example Use:
#include <stdio.h> #include <string.h> #include <cstdarg> static FILE *s_LogHandle = NULL; // Delete trailing newline, if any static void chop(char *buf) { char *p; if ((p = strchr(buf, '\n')) != NULL) { *p = '\0'; } } // *** DECLARING OUR FUNCTION void Log(const char *format, ...) { va_list ap; char buf[5 * 1024]; if (s_LogHandle == NULL) { s_LogHandle = fopen("/tmp/mylog.txt", "at"); } va_start(ap, format); vsnprintf(buf, sizeof(buf), format, ap); chop(buf); fputs(buf, s_LogHandle); fputc('\n', s_LogHandle); fflush(s_LogHandle); va_end(ap); } int main() { int n = 123; Log("The value of n is %d\n", n); // *** USING OUR FUNCTION }
Output of `cat /tmp/mylog.txt`:
The value of n is 123