C
printf-like function
Learn to write your own printf-like function.
printf-like functions with vprintf
If you want to write your own function that behaves like printf, you use vprintf. This function takes a va_list and prints according to the format string.
Signature: void log_msg(const char *level, const char *fmt, ...). Inside, first print the level (printf("%s: ", level)), then va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); to print the formatted part. vprintf is the va_list-taking variant of printf; it uses the same format specifiers (%d, %s, etc.). This pattern is the basis of logging functions. vfprintf and vsprintf similarly write to a file and to a string.
The log_msg example
A real log_msg function combines a level and a formatted message. The output might be INFO: Sum 42.
Definition: void log_msg(const char *level, const char *fmt, ...) { printf("%s: ", level); va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); printf("\n"); }. First the level and colon are printed, then the formatted part with vprintf, finally a newline. The second argument to va_start is fmt because that's the last fixed parameter. Call: log_msg("INFO", "Sum %d", 42). This pattern is the basis of libraries that log at different levels; you can change the level and reuse the same format.
Exercise The log_msg function
Write void log_msg(const char *level, const char *fmt, ...). Start with printf("%s: ", level);. Call va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args);. Finally printf("\n");. In main call log_msg("INFO", "Sum %d", 42);.
Show example solution
#include <stdio.h>
#include <stdarg.h>
void log_msg(const char *level, const char *fmt, ...) {
printf("%s: ", level);
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\n");
}
int main(void) {
log_msg("INFO", "Sum %d", 42);
return 0;
}
Test yourself
-
The vprintf family
- vprintf
- print to screen
- vfprintf
- print to file
- vsprintf
- print to string
- vsnprintf
- print to bounded string
-
The vprintf call
vprintf(fmt, ____);
Show answer
vprintf(fmt, args);
-
What's the difference between vprintf and printf?
- vprintf is slower
- printf takes a va_list
- vprintf takes a va_list
- vprintf takes no format
Show answer
vprintf takes a va_list — vprintf is the va_list-taking variant of printf.
Next lesson: vsnprintf