-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput.c
138 lines (131 loc) · 2.22 KB
/
input.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
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
#include "shell.h"
/**
* get_input - collect user raw input from the shell
* Return: the string
*/
char *get_input(char *msg)
{
char *lineptr = NULL;
size_t n_byte = 0;
int get_byte = 0;
char dir[PATH_MAX];
if (getcwd(dir, sizeof(dir)) == NULL)
{
perror(msg);
}
printf("%s%s$ ", msg, dir);
get_byte = _getline(&lineptr, &n_byte, stdin);
if (get_byte == EOF)
{
free(lineptr);
exit(EXIT_SUCCESS);
/*if (feof(stdin))
{
printf("\n");
free(lineptr);
exit(EXIT_SUCCESS);
}
else
{
perror(msg);
free(lineptr);
exit(EXIT_FAILURE);
}*/
}
return (lineptr);
}
/**
* parse_input - tokenize user input
* @input: the input to tokenize
* Return: the tokenize inputs
*/
char **parse_input(char *input, char *err)
{
char **tokens;
char *token;
char *delim = TOKEN_DELIM;
unsigned int token_size = TOKEN_SIZE;
unsigned int n = 0;
if (!input || !err)
return (NULL);
tokens = malloc(sizeof(char *) * token_size);
if (!tokens)
{
perror(err);
free(tokens);
exit(EXIT_FAILURE);
}
token = strtok(input, delim);
while (token != NULL)
{
tokens[n] = token;
if (++n > token_size)
{
token_size += TOKEN_SIZE;
tokens = realloc(tokens, token_size * sizeof(char *));
if (!tokens)
{
perror(err);
free(tokens);
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, delim);
}
return (tokens);
}
/**
* check_malloc - check if malloc failed
*/
void check_malloc (char *mallocd)
{
if (mallocd == NULL)
{
free(mallocd);
perror(err);
exit(EXIT_FAILURE);
}
}
/**
* getline
* assume that we're working with stdin for the moment which is opened already
* so we don't need to open and close
*/
int _getline(char **lineptr, size_t *n, FILE *stream)
{
char *line;
size_t buf_size = BUF_SIZE;
size_t index = 0;
int c;
(void) stream;
line = malloc(buf_size * sizeof(char));
check_malloc(line);
while(1)
{
c = getchar();
if (c == '\n')
{
line[index] = c;
*n = index;
*lineptr = line;
return (index);
}
else if (c == EOF)
{
free(line);
exit(EXIT_SUCCESS);
}
else
{
line[index] = c;
}
index++;
if (index >= buf_size)
{
buf_size += BUF_SIZE;
line = realloc(*lineptr, buf_size * sizeof(char));
check_malloc(line);
}
}
return (1);
}