aboutsummaryrefslogtreecommitdiffstats
path: root/libft/src/ft_printf_put_precision.c
blob: af7f7b7f0d6e5dac8eabdc27a646de1ad613d301 (plain)
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_printf_put_precision.c                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: rbousset <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/14 17:06:45 by rbousset          #+#    #+#             */
/*   Updated: 2020/02/14 17:06:45 by rbousset         ###   ########lyon.fr   */
/*                                                                            */
/* ************************************************************************** */

#include <libft.h>
#include <stdlib.h>

static int
	ft_printf_get_len(t_printflist *pflist)
{
	if (pflist->conv == 'p' && pflist->precision > pflist->putlen)
		return (pflist->precision - pflist->putlen + 2);
	else if (pflist->precision > pflist->putlen && pflist->isneg == 0
			&& pflist->isaplus == 0)
		return (pflist->precision - pflist->putlen);
	else if (pflist->precision >= pflist->putlen && pflist->isneg == 1)
	{
		if (pflist->isaz == 1)
			return (pflist->precision - pflist->putlen - 1);
		else
			return (pflist->precision - pflist->putlen);
	}
	else if (pflist->precision >= pflist->putlen && pflist->isneg == 0
			&& pflist->isaplus == 1)
	{
		if (pflist->isaz == 1)
			return (pflist->precision - pflist->putlen);
		else
			return (pflist->precision - pflist->putlen + 1);
	}
	return (0);
}

/*
** Puts the correct amount of 0's when
** needed using pflist->precision.
** Used for %p, %d, %i, %u, %x and %X
*/

int
	ft_printf_put_precision(t_printflist *pflist)
{
	char	*str;
	int		len;

	len = 0;
	if (pflist->precision >= pflist->putlen)
	{
		len = ft_printf_get_len(pflist);
		if (!(str = (char*)malloc((len + 1) * sizeof(char))))
			return (1);
		str = ft_memset(str, '0', len);
		*(str + len) = '\0';
		ft_printf_cat_output(str, ft_strlen(str), pflist);
		ft_memdel((void**)&str);
	}
	return (0);
}