I was looking to implement an api like printf for my logging. It should be similar to calling printf. For example:
persistent_log(LogType0, "This is buffered writing %d", i);
I looked into variable argument stuff , but it seems I need to know the number & type of arguments there. so I need more help in that regard.
Similar Functions Other C functions that are similar to the printf function: fprintf function <stdio. h> sprintf function <stdio.
How can printf () and scanf () take multiple arguments? Each argument takes a size of integer in stack. For data types whose sizes are greater than integer, double or multiples of integer size are taken. Inside the function, we take the pointer of the first argument.
C Program 2.1 contains a printf() statement with only one argument, that is, a text string. This string is referred to as the message string and is always the first argument of printf(). It can contain special control characters and/or parameter conversion control characters.
The prototype of printf() is: int printf(char *format, arg1, arg2, ...); printf converts, formats, and prints its arguments on the standard output. It returns the number of characters printed.
Here's an excerpt from a past project that I found to work well for me. Some initialization steps are of course missing. The key here is the vfprintf
function which will handle the details of printing the various arguments.
void _proxy_log(log_level_t level, const char *fmt, ...) __attribute__((format (printf, 2, 3))); #define proxy_log(level, fmt, ...) _proxy_log(level, fmt"\n", ##__VA_ARGS__) void _proxy_log(log_level_t level, const char *fmt, ...) { va_list arg; FILE *log_file = (level == LOG_ERROR) ? err_log : info_log; /* Check if the message should be logged */ if (level > log_level) return; /* Write the error message */ va_start(arg, fmt); vfprintf(log_file, fmt, arg); va_end(arg); #ifdef DEBUG fflush(log_file); fsync(fileno(log_file)); #endif }
Using "va_arg" http://www.cplusplus.com/reference/clibrary/cstdarg/va_arg/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With