Write a program to implement the shell. It should display the command prompt “myshell$”. Tokenize the command line and execute the given command by creating the child process. Additionally it should interpret the following commands.
myshell$ search f filename pattern : To display first occurrence of pattern in the file.
myshell$ search a filename pattern : To search all the occurrence of pattern in the file.
myshell$ search f filename pattern : To display first occurrence of pattern in the file.
myshell$ search a filename pattern : To search all the occurrence of pattern in the file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
// Function to find and print the first occurrence of pattern in the file
void search_first_occurrence(const char *filename, const char *pattern) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
return;
}
char line[1024];
while (fgets(line, sizeof(line), file)) {
if (strstr(line, pattern) != NULL) {
printf("First occurrence: %s", line);
fclose(file);
return;
}
}
printf("Pattern \"%s\" not found in file \"%s\".\n", pattern, filename);
fclose(file);
}
// Function to search and print all occurrences of pattern in the file
void search_all_occurrences(const char *filename, const char *pattern) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
return;
}
char line[1024];
int found = 0;
while (fgets(line, sizeof(line), file)) {
if (strstr(line, pattern) != NULL) {
printf("Occurrence: %s", line);
found = 1;
}
}
if (!found) {
printf("Pattern \"%s\" not found in file \"%s\".\n", pattern, filename);
}
fclose(file);
}
// Function to execute a command in a child process
void execute_command(char **tokens) {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) {
execvp(tokens[0], tokens);
perror("execvp failed");
exit(EXIT_FAILURE);
} else {
int status;
waitpid(pid, &status, 0);
}
}
int main() {
char input[1024];
while (1) {
printf("myshell$ ");
if (fgets(input, sizeof(input), stdin) == NULL) {
perror("fgets failed");
exit(EXIT_FAILURE);
}
// Remove trailing newline character
input[strcspn(input, "\n")] = '\0';
// Tokenize the input
char *tokens[100];
int token_count = 0;
char *token = strtok(input, " ");
while (token != NULL && token_count < 99) {
tokens[token_count++] = token;
token = strtok(NULL, " ");
}
tokens[token_count] = NULL;
// Check if it's a search command
if (token_count >= 3 && strcmp(tokens[0], "search") == 0) {
if (strcmp(tokens[1], "f") == 0 && token_count == 4) {
// search f filename pattern
search_first_occurrence(tokens[2], tokens[3]);
} else if (strcmp(tokens[1], "a") == 0 && token_count == 4) {
// search a filename pattern
search_all_occurrences(tokens[2], tokens[3]);
} else {
printf("Usage: search [f|a] filename pattern\n");
}
} else {
// Execute other commands
execute_command(tokens);
}
}
return 0;
}
0 Comments