-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslip8_2.c
More file actions
113 lines (96 loc) · 2.75 KB
/
slip8_2.c
File metadata and controls
113 lines (96 loc) · 2.75 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
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_CMD_LEN 1024
#define MAX_ARGS 100
void execute_command(char **args) {
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) {
if (execvp(args[0], args) < 0) {
perror("Execution failed");
exit(EXIT_FAILURE);
}
} else {
wait(NULL);
}
}
void tokenize_input(char *input, char **args) {
int index = 0;
char *token = strtok(input, " \n");
while (token != NULL) {
args[index++] = token;
token = strtok(NULL, " \n");
}
args[index] = NULL;
}
void search_command(char *mode, char *filename, char *pattern) {
if (mode == NULL || filename == NULL || pattern == NULL) {
fprintf(stderr, "Usage: search <f|c> <filename> <pattern>\n");
return;
}
FILE *file = fopen(filename, "r");
if (!file) {
perror("File open failed");
return;
}
char line[1024];
int found = 0;
int count = 0;
while (fgets(line, sizeof(line), file)) {
if (strstr(line, pattern)) {
if (strcmp(mode, "f") == 0) {
printf("%s", line);
found = 1;
break;
} else if (strcmp(mode, "c") == 0) {
char *ptr = line;
while ((ptr = strstr(ptr, pattern)) != NULL) {
count++;
ptr++;
}
}
}
}
if (strcmp(mode, "c") == 0) {
printf("Total occurrences: %d\n", count);
} else if (strcmp(mode, "f") == 0 && !found) {
printf("Pattern not found.\n");
}
fclose(file);
}
int main() {
char input[MAX_CMD_LEN];
char *args[MAX_ARGS];
while (1) {
printf("myshell$ ");
if (fgets(input, sizeof(input), stdin) == NULL) {
perror("fgets failed");
continue;
}
if (strlen(input) <= 1) continue;
tokenize_input(input, args);
if (args[0] == NULL) continue;
if (strcmp(args[0], "exit") == 0) {
exit(0);
} else if (strcmp(args[0], "cd") == 0) {
if (args[1] == NULL) {
fprintf(stderr, "cd: missing argument\n");
} else {
if (chdir(args[1]) != 0) {
perror("cd failed");
}
}
} else if (strcmp(args[0], "search") == 0) {
search_command(args[1], args[2], args[3]);
} else {
execute_command(args);
}
}
return 0;
}