Created
January 10, 2015 21:27
-
-
Save brimston3/cbbcd9b03349936f8f64 to your computer and use it in GitHub Desktop.
Example of C variadic macros and some vfprintf wrapping.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if you need a license, BSDNEW.