Skip to content

Instantly share code, notes, and snippets.

@swt02026
Created April 23, 2018 06:16
Show Gist options
  • Save swt02026/710da0b482039687d40ebda0b6fe030d to your computer and use it in GitHub Desktop.
Save swt02026/710da0b482039687d40ebda0b6fe030d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <printf.h>
struct widget {
size_t length;
size_t width;
};
int print_widget(FILE *const stream, const struct printf_info *const info,
const void *const *args) {
const struct widget *const mywidget = *((const struct widget **)(args[0]));
char *buffer = NULL;
int len = asprintf(&buffer, "<widget %p: len=%zu, width=%zu>", mywidget,
mywidget->length, mywidget->width);
if (len < 0)
return -1;
len =
fprintf(stream, "%*s", (info->left ? -info->width : info->width), buffer);
free(buffer);
}
int print_widget_arginfo(const struct printf_info *const info, const size_t n,
int *const argtypes) {
/* We always take exactly one argument and this is a pointer to the
structure.. */
if (n > 0)
argtypes[0] = PA_POINTER;
return 1;
}
int main() {
struct widget *const mywidget = &(struct widget){.length = 5, .width = 6};
register_printf_function('W', print_widget, print_widget_arginfo);
printf("%W\n", mywidget);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment