format.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
  3. * See the copyright notice in the ACK home directory, in the file "Copyright".
  4. */
  5. /* $Id$ */
  6. #include <string.h>
  7. #include <system.h>
  8. #include "print.h"
  9. static int integral(int c)
  10. {
  11. switch (c) {
  12. case 'b':
  13. return -2;
  14. case 'd':
  15. return 10;
  16. case 'o':
  17. return -8;
  18. case 'u':
  19. return -10;
  20. case 'x':
  21. return -16;
  22. }
  23. return 0;
  24. }
  25. /*FORMAT1 $
  26. %s = char *
  27. %l = long
  28. %c = int
  29. %[uxbo] = unsigned int
  30. %d = int
  31. $ */
  32. int _format(char *buf, char *fmt, va_list argp)
  33. {
  34. register char *pf = fmt;
  35. register char *pb = buf;
  36. while (*pf) {
  37. if (*pf == '%') {
  38. register width, base, pad, npad;
  39. char *arg;
  40. char cbuf[2];
  41. char *badformat = "<bad format>";
  42. /* get padder */
  43. if (*++pf == '0') {
  44. pad = '0';
  45. ++pf;
  46. }
  47. else
  48. pad = ' ';
  49. /* get width */
  50. width = 0;
  51. while (*pf >= '0' && *pf <= '9')
  52. width = 10 * width + *pf++ - '0';
  53. if (*pf == 's') {
  54. arg = va_arg(argp, char *);
  55. }
  56. else
  57. if (*pf == 'c') {
  58. cbuf[0] = va_arg(argp, int);
  59. cbuf[1] = '\0';
  60. arg = &cbuf[0];
  61. }
  62. else
  63. if (*pf == 'l') {
  64. /* alignment ??? */
  65. if ((base = integral(*++pf))) {
  66. arg = long2str(va_arg(argp,long), base);
  67. }
  68. else {
  69. pf--;
  70. arg = badformat;
  71. }
  72. }
  73. else
  74. if ((base = integral(*pf))) {
  75. arg = long2str((long)va_arg(argp,int), base);
  76. }
  77. else
  78. if (*pf == '%')
  79. arg = "%";
  80. else
  81. arg = badformat;
  82. npad = width - strlen(arg);
  83. while (npad-- > 0)
  84. *pb++ = pad;
  85. while (((*pb++) = (*arg++)));
  86. pb--;
  87. pf++;
  88. }
  89. else
  90. *pb++ = *pf++;
  91. }
  92. return pb - buf;
  93. }