Skip to content

Instantly share code, notes, and snippets.

@brimston3
Created January 10, 2015 21:27
Show Gist options
  • Save brimston3/cbbcd9b03349936f8f64 to your computer and use it in GitHub Desktop.
Save brimston3/cbbcd9b03349936f8f64 to your computer and use it in GitHub Desktop.
Example of C variadic macros and some vfprintf wrapping.
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <time.h>
#define printfTS(msg, ...) fprintfTS(stdout, msg, ## __VA_ARGS__)
// This is *not* threadsafe (localtime & strftime)
int fprintfTS(FILE * stream, const char * const msg, ...)
{
int rc = 0;
time_t t;
struct tm *now_p;
char datetime[20] = "";
va_list arg;
time(&t);
now_p = localtime(&t);
strftime(datetime, sizeof(datetime), "%H:%M:%S", now_p);
fprintf(stream, "%s - ", datetime);
va_start (arg, msg);
rc = vfprintf(stream, msg, arg);
va_end(arg);
return rc;
}
int main()
{
fprintfTS(stdout, "Some random message #1\n");
printfTS("Some random message #%d\n", 2);
return 0;
}
@brimston3
Copy link
Author

if you need a license, BSDNEW.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment