-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_putnbr_fd.c
72 lines (67 loc) · 2.11 KB
/
ft_putnbr_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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putnbr_fd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nholbroo <nholbroo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/23 17:25:21 by nholbroo #+# #+# */
/* Updated: 2025/02/03 17:05:34 by nholbroo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
Helper function for ft_putnbr_fd(). This is where the actual conversion and
writing happens.
@param str The string that will store the converted number.
@param n The integer value to be converted and written.
@param fd The file descriptor (1 for stdout, 2 for stderr, etc.)
*/
static void ft_nbwrite(char *str, int n, int fd)
{
int i;
i = 0;
while (n > 0)
{
str[i] = n % 10 + '0';
n /= 10;
i++;
}
str[i--] = '\0';
while (i >= 0)
write(fd, &str[i--], 1);
}
/*
Which function:
Not a standard function in C.
Definition:
The ft_putnbr_fd() function writes a number of type integer to the file
descriptor (fd). It converts the number from integer to ascii, and then
writes it to fd.
Return values:
None.
@param n The integer value to be converted and written.
@param fd The file descriptor (1 for stdout, 2 for stderr, etc.)
@param str The string that will store the converted number. Statically allocated
to 12 bytes, to be able to handle all possible integer values.
*/
void ft_putnbr_fd(int n, int fd)
{
char str[12];
if (n == -2147483648)
{
write(fd, "-2147483648", 11);
return ;
}
if (n == 0)
{
write(fd, "0", 1);
return ;
}
if (n < 0)
{
n *= -1;
write(fd, "-", 1);
}
ft_nbwrite(str, n, fd);
}