forked from vvy/wshell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_command.c
115 lines (104 loc) · 2.5 KB
/
read_command.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
/*
* =====================================================================================
* Filename: read_command.c
* Description:
* Version: 1.0
* Created: 2013.10.21 14h12min24s
* Author: wuyue (wy), [email protected]
* Company: UESTC
* =====================================================================================
*/
#include "wshell.h"
#ifdef READLINE_ON
#include <readline/readline.h>
#include <readline/history.h>
#endif
//return value: number of parameters
//0 represents only command without any parameters
//-1 represents wrong input
int read_command(char **command,char **parameters,char *prompt)
{
#ifdef READLINE_ON
free(buffer);
buffer = readline(prompt);
if(feof(stdin)) {
printf("\n");
exit(0);
}
#else
printf("%s",prompt);
char* Res_fgets = fgets(buffer,MAXLINE,stdin);
if(Res_fgets == NULL)
{
printf("\n");
exit(0);
}
#endif
if(buffer[0] == '\0')
return -1;
char *pStart,*pEnd;
int count = 0;
int isFinished = 0;
pStart = pEnd = buffer;
while(isFinished == 0)
{
while((*pEnd == ' ' && *pStart == ' ') || (*pEnd == '\t' && *pStart == '\t'))
{
pStart++;
pEnd++;
}
if(*pEnd == '\0' || *pEnd == '\n')
{
if(count == 0)
return -1;
break;
}
while(*pEnd != ' ' && *pEnd != '\0' && *pEnd != '\n')
pEnd++;
if(count == 0)
{
char *p = pEnd;
*command = pStart;
while(p!=pStart && *p !='/')
p--;
if(*p == '/')
p++;
//else //p==pStart
parameters[0] = p;
count += 2;
#ifdef DEBUG
printf("\ncommand:%s\n",*command);
#endif
}
else if(count <= MAXARG)
{
parameters[count-1] = pStart;
count++;
}
else
{
break;
}
if(*pEnd == '\0' || *pEnd == '\n')
{
*pEnd = '\0';
isFinished = 1;
}
else
{
*pEnd = '\0';
pEnd++;
pStart = pEnd;
}
}
parameters[count-1] = NULL;
#ifdef DEBUG
/*input analysis*/
printf("input analysis:\n");
printf("pathname:[%s]\ncommand:[%s]\nparameters:\n",*command,parameters[0]);
int i;
for(i=0;i<count-1;i++)
printf("[%s]\n",parameters[i]);
#endif
return count;
}