-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyshell.c
More file actions
80 lines (80 loc) · 1.17 KB
/
Copy pathmyshell.c
File metadata and controls
80 lines (80 loc) · 1.17 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
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void make_toks(char *s, char *tok[])
{
int i = 0;
char *p;
p = strtok(s, " ");
while (p != NULL)
{
tok[i++] = p;
p = strtok(NULL, " ");
}
tok[i] = NULL;
}
void count(char *fn, char op)
{
int fh, cc = 0, wc = 0, lc = 0;
char c;
fh = open(fn, O_RDONLY);
if (fh == -1)
{
printf("File %s not found.\n", fn);
return;
}
while (read(fh, &c, 1) > 0)
{
if (c == ' ')
wc++;
else if (c == '\n')
{
wc++;
lc++;
}
cc++;
}
close(fh);
switch (op)
{
case 'c':
printf("No.of characters:%d\n", cc - 1);
break;
case 'w':
printf("No.of words:%d\n", wc);
break;
case 'l':
printf("No.of lines:%d\n", lc + 1);
break;
}
}
int main()
{
char buff[80], *args[10];
int pid;
while (1)
{
printf("myshell$ ");
fflush(stdin);
fgets(buff, 80, stdin);
buff[strlen(buff) - 1] = '\0';
make_toks(buff, args);
if (strcmp(args[0], "count") == 0)
count(args[2], args[1][0]);
else
{
pid = fork();
if (pid > 0)
wait();
else
{
if (execvp(args[0], args) == -1)
printf("Bad command.\n");
}
}
}
return 0;
}