-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.c
More file actions
109 lines (94 loc) · 2.88 KB
/
utils.c
File metadata and controls
109 lines (94 loc) · 2.88 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nde-maes <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/04 13:29:27 by nde-maes #+# #+# */
/* Updated: 2019/02/25 12:10:31 by nde-maes ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
/*
** `create_str_of_len_char` basically creates a string of length `len` (trailing
** 0 not included) and fills it with the character `c`.
*/
char *create_str_of_len_char(char c, int len)
{
char *str;
if (!(str = (char*)malloc(len + 1)))
exit(-1);
str[len] = 0;
while (len--)
str[len] = c;
return (str);
}
/*
** `realloc_with_add_on_left` reallocates the string `str` with the string
** `left_str` appended to it. It also frees its pointer, so that it's possible
** to call the function and store its result with the same pointer `str`.
** Note: `left_str` is not freed, you need to free it yourself once you're done
** with it.
*/
char *realloc_with_add_on_left(char *str, char *left_str)
{
char *ns;
if (!str || !left_str)
exit(-1);
if (!(ns = ft_strnew(ft_strlen(str) + ft_strlen(left_str))))
exit(-1);
ft_strcpy(ns, left_str);
ft_strcat(ns, str);
free(str);
return (ns);
}
/*
** `realloc_with_add_on_right` works the same than `realloc_with_add_on_left`
** except that instead of adding a string on the left, it adds it on the right.
*/
char *realloc_with_add_on_right(char *str, char *right_str)
{
char *ns;
if (!str || !right_str)
exit(-1);
if (!(ns = ft_strnew(ft_strlen(str) + ft_strlen(right_str))))
exit(-1);
ft_strcpy(ns, str);
ft_strcat(ns, right_str);
free(str);
return (ns);
}
/*
** `ft_strnjoin` concatenates an arbitrary `nb_args` amount of string arguments
** into one single string.
** Note: the merged strings don't freed. Free them yourself is if needed.
*/
char *ft_strnjoin(int nb_args, ...)
{
va_list ap;
int i;
char *str;
char *right;
if (!(str = (char*)malloc(1)))
exit(-1);
str[0] = 0;
va_start(ap, nb_args);
i = -1;
while (++i < nb_args)
{
right = va_arg(ap, char*);
str = realloc_with_add_on_right(str, right);
}
va_end(ap);
return (str);
}
/*
** Just a trick on the Norm to get ft_printf fits in 25 lines max.
** It's ugly, I know.
*/
void putchar_and_increment_ret(char c, int *ret)
{
ft_putchar(c);
(*ret)++;
}