]>
Commit | Line | Data |
---|---|---|
d9a17c07 | 1 | /* Printf Extension Example |
f7a9f785 | 2 | Copyright (C) 1991-2016 Free Software Foundation, Inc. |
d9a17c07 RM |
3 | |
4 | This program is free software; you can redistribute it and/or | |
5 | modify it under the terms of the GNU General Public License | |
6 | as published by the Free Software Foundation; either version 2 | |
7 | of the License, or (at your option) any later version. | |
8 | ||
9 | This program is distributed in the hope that it will be useful, | |
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | GNU General Public License for more details. | |
13 | ||
14 | You should have received a copy of the GNU General Public License | |
15 | along with this program; if not, if not, see <http://www.gnu.org/licenses/>. | |
16 | */ | |
17 | ||
28f540f4 | 18 | #include <stdio.h> |
118bad87 | 19 | #include <stdlib.h> |
28f540f4 | 20 | #include <printf.h> |
28f540f4 RM |
21 | |
22 | /*@group*/ | |
23 | typedef struct | |
118bad87 UD |
24 | { |
25 | char *name; | |
26 | } | |
27 | Widget; | |
28f540f4 RM |
28 | /*@end group*/ |
29 | ||
54d79e99 | 30 | int |
838e5ffe UD |
31 | print_widget (FILE *stream, |
32 | const struct printf_info *info, | |
118bad87 | 33 | const void *const *args) |
28f540f4 | 34 | { |
118bad87 | 35 | const Widget *w; |
28f540f4 RM |
36 | char *buffer; |
37 | int len; | |
38 | ||
39 | /* Format the output into a string. */ | |
118bad87 | 40 | w = *((const Widget **) (args[0])); |
28f540f4 RM |
41 | len = asprintf (&buffer, "<Widget %p: %s>", w, w->name); |
42 | if (len == -1) | |
43 | return -1; | |
44 | ||
45 | /* Pad to the minimum field width and print to the stream. */ | |
46 | len = fprintf (stream, "%*s", | |
118bad87 | 47 | (info->left ? -info->width : info->width), |
28f540f4 RM |
48 | buffer); |
49 | ||
50 | /* Clean up and return. */ | |
51 | free (buffer); | |
52 | return len; | |
53 | } | |
54 | ||
55 | ||
54d79e99 UD |
56 | int |
57 | print_widget_arginfo (const struct printf_info *info, size_t n, | |
58 | int *argtypes) | |
59 | { | |
60 | /* We always take exactly one argument and this is a pointer to the | |
61 | structure.. */ | |
62 | if (n > 0) | |
63 | argtypes[0] = PA_POINTER; | |
64 | return 1; | |
65 | } | |
66 | ||
67 | ||
28f540f4 RM |
68 | int |
69 | main (void) | |
70 | { | |
71 | /* Make a widget to print. */ | |
72 | Widget mywidget; | |
73 | mywidget.name = "mywidget"; | |
74 | ||
75 | /* Register the print function for widgets. */ | |
54d79e99 | 76 | register_printf_function ('W', print_widget, print_widget_arginfo); |
28f540f4 RM |
77 | |
78 | /* Now print the widget. */ | |
79 | printf ("|%W|\n", &mywidget); | |
80 | printf ("|%35W|\n", &mywidget); | |
81 | printf ("|%-35W|\n", &mywidget); | |
82 | ||
83 | return 0; | |
84 | } |