-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_putnbr_base_fd.c
88 lines (78 loc) · 2.15 KB
/
ft_putnbr_base_fd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putnbr_base_fd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ldulling <ldulling@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/22 19:26:15 by ldulling #+# #+# */
/* Updated: 2023/10/22 19:26:16 by ldulling ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static size_t baselen(const char *base);
static int check_for_duplicate(const char *base, size_t len);
static int print(unsigned long u_n, const char *base, size_t len, int fd);
int ft_putnbr_base_fd(long n, const char *base, int fd)
{
size_t len;
unsigned long u_n;
int written;
if (base == NULL || fd < 0)
return (0);
len = baselen(base);
if (len < 2 || check_for_duplicate(base, len))
return (0);
written = 0;
if (n < 0)
{
if (write(fd, "-", 1) == 1)
written += 1;
u_n = (unsigned long) n * -1;
}
else
u_n = (unsigned long) n;
written += print(u_n, base, len, fd);
return (written);
}
static size_t baselen(const char *base)
{
size_t len;
len = 0;
while (base[len])
{
if (base[len] == '+' || base[len] == '-')
return (0);
len++;
}
return (len);
}
static int check_for_duplicate(const char *base, size_t len)
{
size_t i;
size_t j;
i = 0;
while (i < len - 1)
{
j = i + 1;
while (j < len)
{
if (base[i] == base[j])
return (1);
j++;
}
i++;
}
return (0);
}
static int print(unsigned long u_n, const char *base, size_t len, int fd)
{
int written;
written = 0;
if (u_n >= len)
written += print(u_n / len, base, len, fd);
u_n %= len;
if (write(fd, &base[u_n], 1) == 1)
written += 1;
return (written);
}