-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils2.c
More file actions
138 lines (112 loc) · 2.07 KB
/
utils2.c
File metadata and controls
138 lines (112 loc) · 2.07 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include "main.h"
/**
* _strcmp- compare two strings
* @str1: the first string
* @str2: the second string
* Return: 0 true, -1 false
*/
int _strcmp(char *str1, char *str2)
{
while (*str1 || *str2)
{
if (*str1 != *str2)
return (0);
str1++;
str2++;
}
return (1);
}
/**
* _strdup- copy string
* @str: string to copy
* Return: string result
*/
char *_strdup(char *str)
{
int len = _strlen(str), i;
char *res = malloc(sizeof(char) * (len + 1));
if (!str)
return (NULL);
if (res == NULL)
{
perror("strdup Error!");
return (NULL);
}
for (i = 0; str[i]; i++)
res[i] = str[i];
res[len] = '\0';
return (res);
}
/**
* _strlen_2d- the length of array of strings
* @str: the array of string
* Return: the length
*/
int _strlen_2d(char **str)
{
int i = 0;
while (str[i] != NULL)
i++;
return (i);
}
/**
* _split- SPlitting a string at a delim
* @buffer: the string
* @delim: the delimeter
* Return: Splitted string
*/
char **_split(char *buffer, char *delim)
{
char **args = NULL, *str;
int i = 0, size = 10;
args = (char **)malloc(sizeof(char *) * size);
if (args == NULL)
{
perror("Malloc _split Error!");
return (NULL);
}
str = strtok(buffer, delim);
while (str)
{
if (i == size)
{
args = _realloc(args, size * sizeof(char *), (size + 16) * sizeof(char *));
if (args == NULL)
_perr_free2d_exit1("_split _realloc Error!", args);
}
args[i] = _strdup(str);
if (args[i] == NULL)
_perr_free2d_exit1("_split _strdup Error!", args);
i++;
str = strtok(NULL, delim);
}
args[i] = NULL;
return (args);
}
/**
* _realloc- realloc built-in
* @ptr: the old buffer
* @new_size: the new length
* @old_size: the old length
* Return: new malloc with new size
*/
void *_realloc(void *ptr, int old_size, int new_size)
{
int i;
char *new_ptr;
if (new_size == 0)
{
free(ptr);
return (NULL);
}
new_ptr = malloc(new_size);
if (new_ptr == NULL)
return (NULL);
if (ptr != NULL && old_size < new_size)
{
for (i = 0; i < old_size; i++)
*((char *)new_ptr + i) = *((char *)ptr + i);
}
free(ptr);
return (new_ptr);
}