-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patharguments.c
90 lines (73 loc) · 1.34 KB
/
arguments.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
#include "main.h"
/**
* _get_cmd_ - get command from stdin
* Return: char ptr
*/
char *_get_cmd_(void)
{
char *line = NULL;
size_t bufsize = 0;
ssize_t characters;
write(STDIN_FILENO, "($) ", 4);
characters = getline(&line, &bufsize, stdin);
if (characters == -1)
{
if (feof(stdin))
{
write(STDOUT_FILENO, "\n", 2);
exit(EXIT_SUCCESS);
}
else
{
perror("readline error");
exit(EXIT_FAILURE);
}
}
return (line);
}
/**
* getArgs - get arguments from command line
* @line: command line
* Return: char ptr
*/
char **getArgs(char *line)
{
int buffer_size = 64, i = 0;
char *token, **args = malloc(buffer_size * sizeof(char *));
if (!args)
{
perror("Unable to allocate memory\n");
exit(EXIT_FAILURE);
}
/* Check if the line is empty or only contains whitespace */
if (line == NULL || line[0] == '\n' || line[0] == ' ')
{
/* Re-prompt again */
interactive();
}
token = _strtok(line, DELIM);
while (token != NULL)
{
if (token[0] == '#')
{
/* Handle comments and whitespace */
break;
}
args[i] = token;
i++;
if (i >= buffer_size)
{
buffer_size += 64;
args = _realloc(args, buffer_size * sizeof(char *));
if (!args)
{
perror("Unable to allocate memory\n");
exit(EXIT_FAILURE);
}
}
token = _strtok(NULL, DELIM);
}
free(token);
args[i] = NULL;
return (args);
}