format.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. extern char *long2str();
  10. static int
  11. integral(c)
  12. {
  13. switch (c) {
  14. case 'b':
  15. return -2;
  16. case 'd':
  17. return 10;
  18. case 'o':
  19. return -8;
  20. case 'u':
  21. return -10;
  22. case 'x':
  23. return -16;
  24. }
  25. return 0;
  26. }
  27. /*FORMAT1 $
  28. %s = char *
  29. %l = long
  30. %c = int
  31. %[uxbo] = unsigned int
  32. %d = int
  33. $ */
  34. int
  35. _format(buf, fmt, argp)
  36. char *buf, *fmt;
  37. register va_list argp;
  38. {
  39. register char *pf = fmt;
  40. register char *pb = buf;
  41. while (*pf) {
  42. if (*pf == '%') {
  43. register width, base, pad, npad;
  44. char *arg;
  45. char cbuf[2];
  46. char *badformat = "<bad format>";
  47. /* get padder */
  48. if (*++pf == '0') {
  49. pad = '0';
  50. ++pf;
  51. }
  52. else
  53. pad = ' ';
  54. /* get width */
  55. width = 0;
  56. while (*pf >= '0' && *pf <= '9')
  57. width = 10 * width + *pf++ - '0';
  58. if (*pf == 's') {
  59. arg = va_arg(argp, char *);
  60. }
  61. else
  62. if (*pf == 'c') {
  63. cbuf[0] = va_arg(argp, int);
  64. cbuf[1] = '\0';
  65. arg = &cbuf[0];
  66. }
  67. else
  68. if (*pf == 'l') {
  69. /* alignment ??? */
  70. if (base = integral(*++pf)) {
  71. arg = long2str(va_arg(argp,long), base);
  72. }
  73. else {
  74. pf--;
  75. arg = badformat;
  76. }
  77. }
  78. else
  79. if (base = integral(*pf)) {
  80. arg = long2str((long)va_arg(argp,int), base);
  81. }
  82. else
  83. if (*pf == '%')
  84. arg = "%";
  85. else
  86. arg = badformat;
  87. npad = width - strlen(arg);
  88. while (npad-- > 0)
  89. *pb++ = pad;
  90. while (*pb++ = *arg++);
  91. pb--;
  92. pf++;
  93. }
  94. else
  95. *pb++ = *pf++;
  96. }
  97. return pb - buf;
  98. }