-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_getopt.c
80 lines (74 loc) · 2.16 KB
/
ft_getopt.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_getopt.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lbopp <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/09 09:59:44 by lbopp #+# #+# */
/* Updated: 2017/01/17 12:09:26 by lbopp ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_getopt.h"
#include "libft.h"
char *g_optarg = 0;
int g_optind = 1;
int g_optopt = 0;
int g_opterr = 1;
int g_optreset = 0;
int treatment_opt(const char *av[], int *i, const char *optstring, int *end)
{
if (av[g_optind] && !av[g_optind][*i + 1])
*end += 1;
if (ft_strchr(optstring, av[g_optind][*i]))
{
*i += 1;
g_optopt = av[g_optind][*i - 1];
return (av[g_optind][*i - 1]);
}
else
{
if (g_opterr)
{
write(1, av[0], ft_strlen(av[0]));
write(1, ": illegal option -- ", 20);
write(1, &(av[g_optind][*i]), 1);
write(1, "\n", 1);
}
*i += 1;
g_optopt = av[g_optind][*i - 1];
return ('?');
}
}
void reset(int *i)
{
g_optind++;
*i = 1;
}
int ft_getopt(int ac, const char *av[], const char *optstring)
{
static int i = 1;
static int end = 0;
if (end)
{
reset(&i);
end = 0;
}
if (ac >= 2)
{
if (av[g_optind] && av[g_optind][0] == '-' && av[g_optind][1] == '-')
{
g_optind++;
return (-1);
}
if (av[g_optind] && av[g_optind][0] == '-' && av[g_optind][1] == '\0')
return (-1);
else if (av[g_optind] && av[g_optind][i] == '\0' &&
av[g_optind][0] == '-')
reset(&i);
if (av[g_optind] && av[g_optind][i] && av[g_optind][0] == '-' &&
av[g_optind][i] != '-')
return (treatment_opt(av, &i, optstring, &end));
}
return (-1);
}