pf_p.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* pf_p.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: bchanot <bchanot@students.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2016/02/27 01:51:30 by bchanot #+# #+# */
  9. /* Updated: 2016/05/29 04:03:02 by bchanot ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "libftprintf.h"
  13. #include <stdlib.h>
  14. static int pf_width_p(char *str, t_inf inf, int len, void *p)
  15. {
  16. int i;
  17. i = p == (void *)0 && inf.prec == -1 ? 0 : (int)ft_strlen(str);
  18. if (inf.prec > i)
  19. {
  20. if (len < inf.width - inf.prec)
  21. return (1);
  22. }
  23. else if (len < inf.width - i)
  24. return (1);
  25. return (0);
  26. }
  27. static char get_digit(int n)
  28. {
  29. if (n >= 0 && n <= 9)
  30. return (n + '0');
  31. return (n - 10 + 'a');
  32. }
  33. static char *ft_ptoa(void *p)
  34. {
  35. unsigned long tmpn;
  36. unsigned long n;
  37. int len;
  38. char *str;
  39. n = (unsigned long)p;
  40. tmpn = (unsigned long)p;
  41. len = 2;
  42. while (tmpn /= 16)
  43. len++;
  44. if ((str = (char*)malloc(sizeof(char) * len)) == NULL)
  45. return (NULL);
  46. str[--len] = '\0';
  47. while (len--)
  48. {
  49. str[len] = get_digit(n % 16);
  50. n = n / 16;
  51. }
  52. return (str);
  53. }
  54. static int pf_p2(char *str, t_inf inf, int len)
  55. {
  56. len += pf_putstr(str, inf.fd);
  57. if (inf.width > 0 && inf.min == 1)
  58. while (len < inf.width && len++ >= 0)
  59. ft_putchar_fd(' ', inf.fd);
  60. if (str)
  61. free(str);
  62. return (len);
  63. }
  64. int pf_p(va_list ap, t_inf inf)
  65. {
  66. char *str;
  67. int len;
  68. void *p;
  69. int cpt;
  70. p = va_arg(ap, void*);
  71. str = ft_ptoa(p);
  72. len = 2;
  73. if (inf.zero && inf.prec != 0)
  74. inf.zero = 0;
  75. if (inf.width > 0 && !inf.min && !inf.zero && inf.width > inf.prec)
  76. while (pf_width_p(str, inf, len, p) && len++ >= 0)
  77. ft_putchar_fd(' ', inf.fd);
  78. pf_putstr("0x", inf.fd);
  79. cpt = -1;
  80. if (inf.prec > 0)
  81. while (++cpt < inf.prec - ((int)ft_strlen(str)) && len++ >= 0)
  82. ft_putchar_fd('0', inf.fd);
  83. cpt = -1;
  84. if (inf.width && inf.zero && !inf.min)
  85. while (++cpt < inf.width - ((int)ft_strlen(str) + 2) && len++ >= 0)
  86. ft_putchar_fd('0', inf.fd);
  87. return (pf_p2(str, inf, len));
  88. }