-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_utils_bonus.c
109 lines (101 loc) · 2.57 KB
/
get_next_line_utils_bonus.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/* ************************************************************************** */
/* */
/* :::::::: */
/* get_next_line_utils_bonus.c :+: :+: */
/* +:+ */
/* By: cherrewi <[email protected]> +#+ */
/* +#+ */
/* Created: 2022/10/30 14:34:08 by cherrewi #+# #+# */
/* Updated: 2022/11/14 15:12:08 by cherrewi ######## odam.nl */
/* */
/* ************************************************************************** */
#include <stdlib.h>
/*
Locates the first occurrence of c (converted to a char) in string s.
returns NULL if the character does not appear in the string
*/
char *ft_strchr(const char *s, int c)
{
if (s == NULL)
return (NULL);
if ((char)c == 0)
{
while (*s)
s++;
return ((char *)s);
}
else
{
while (*s)
{
if (*s == (char)c)
return ((char *)s);
s++;
}
}
return (NULL);
}
size_t ft_strlen(const char *s)
{
size_t c;
if (s == NULL)
return (0);
c = 0;
while (*s)
{
s++;
c++;
}
return (c);
}
/*
Copies src to dst; always null terminates
Returns the length of src (excl. null terminator)
*/
size_t ft_strlcpy(char *dst, const char *src, size_t dstsize)
{
size_t src_len;
size_t i;
src_len = ft_strlen(src);
if (dstsize == 0)
return (src_len);
i = 0;
while (i < src_len && i < dstsize - 1)
{
dst[i] = src[i];
i++;
}
dst[i] = '\0';
return (src_len);
}
/*
copies a substring to new memory
starting at position 'start' not more than 'len' chars
copies not more chars than present in the string
one extra byte is allocated for the new string, so it is null terminated
note: 'start' is a zero-based index!
if malloc fails, NULL is returned
*/
char *ft_substr(char const *s, unsigned int start, size_t len)
{
size_t i;
char *new_str;
if (s == NULL)
return (NULL);
if (start > ft_strlen(s))
new_str = malloc(1 * sizeof(char));
else if (ft_strlen(s) - start > len)
new_str = malloc(len + 1 * sizeof(char));
else
new_str = malloc((ft_strlen(s) - start + 1) * sizeof(char));
if (new_str == NULL)
return (NULL);
i = 0;
while (i < ft_strlen(s) - start && i < len && start < ft_strlen(s))
{
new_str[i] = s[i + start];
i++;
}
new_str[i] = '\0';
return (new_str);
}