ft_printf.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* ft_printf.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: bchanot <bchanot@students.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2016/02/11 00:22:06 by bchanot #+# #+# */
  9. /* Updated: 2018/10/14 03:40:26 by bchanot ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "libftprintf.h"
  13. #include <unistd.h>
  14. static int (*g_func[])(va_list, t_inf) = {
  15. pf_percent, pf_s, pf_s_up, pf_p,
  16. pf_di, pf_d_up, pf_di, pf_o,
  17. pf_o_up, pf_u, pf_u_up, pf_x,
  18. pf_x_up, pf_c, pf_c_up, pf_b};
  19. int pf_print_part(const char *format, char *s, int fd)
  20. {
  21. int len;
  22. len = 0;
  23. while (format + len != s)
  24. len++;
  25. write(fd, format, len);
  26. return (len);
  27. }
  28. static int ft_format(char **s, va_list ap, t_inf inf)
  29. {
  30. int len;
  31. len = 0;
  32. if (inf.type == -1)
  33. return (-2);
  34. else if (inf.type >= 0)
  35. len = g_func[inf.type](ap, inf);
  36. if (len < 0)
  37. return (-1);
  38. *s -= 1;
  39. return (len);
  40. }
  41. static int pf_printf(const char **format, va_list ap, char **s, int tmp[2])
  42. {
  43. int chk;
  44. t_inf inf;
  45. int len;
  46. len = tmp[0];
  47. len += pf_print_part(*format, *s, tmp[1]);
  48. *s += 1;
  49. inf = pf_take_inf(s, ap, tmp[1]);
  50. if ((chk = ft_format(s, ap, inf)) < 0)
  51. {
  52. if (chk == -1)
  53. return (-1);
  54. if (pf_wrong_conv(s, format, inf, &len))
  55. return (len);
  56. }
  57. else
  58. {
  59. *format = *s + 1;
  60. len += chk;
  61. }
  62. return (len);
  63. }
  64. int ft_printf(int fd, const char *format, ...)
  65. {
  66. va_list ap;
  67. int len[2];
  68. char *s;
  69. int col;
  70. len[0] = 0;
  71. len[1] = fd;
  72. col = 0;
  73. s = (char *)format;
  74. va_start(ap, format);
  75. while (*s)
  76. {
  77. if (*s == '{')
  78. col = pf_take_color(&s, &format, &len[0], len[1]);
  79. if (*s == '%')
  80. if ((len[0] = pf_printf(&format, ap, &s, len) == -1))
  81. return (-1);
  82. s++;
  83. }
  84. va_end(ap);
  85. len[0] += pf_putstr(format, fd);
  86. if (col == 1)
  87. ft_putstr_fd(EOC, fd);
  88. return (len[0]);
  89. }