rprintf.c 2.0 KB

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