Write a C program that behaves like a shell which displays the command prompt ‘myshell$’. It accepts the command, tokenize the command line and execute it by creating the child process. Also implement the additional command ‘search’ as myshell$ search f filename pattern : It will search the first occurrence of pattern in the given file myshell$ search a filename pattern : It will search all the occurrence of pattern in the given file myshell$ search c filename pattern : It will count the number of occurrence of pattern in the given file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#define MAX_INPUT_SIZE 1024
#define MAX_ARGS 10
void execute_command(char *args[], int count) {
pid_t pid = fork();
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
execvp(args[0], args);
perror("execvp failed");
exit(EXIT_FAILURE);
} else {
// Parent process
wait(NULL); // Wait for the child to complete
}
}
void search_file(char *filename, char *pattern, char *option) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("fopen");
return;
}
char line[MAX_INPUT_SIZE];
int count = 0;
int found = 0;
while (fgets(line, sizeof(line), file)) {
if (strstr(line, pattern) != NULL) {
found = 1;
count++;
if (strcmp(option, "f") == 0) {
printf("Found at line %d: %s", count, line);
break; // Stop after finding the first occurrence if searching first occurrence
} else if (strcmp(option, "a") == 0) {
printf("Found at line %d: %s", count, line);
}
}
}
fclose(file);
if (strcmp(option, "c") == 0) {
printf("Pattern '%s' found %d times in %s\n", pattern, count, filename);
} else if (!found) {
printf("Pattern '%s' not found in %s\n", pattern, filename);
}
}
int main() {
char input[MAX_INPUT_SIZE];
char *args[MAX_ARGS];
int arg_count;
while (1) {
printf("myshell$ ");
if (fgets(input, sizeof(input), stdin) == NULL) {
break; // Exit the loop on EOF
}
input[strcspn(input, "\n")] = 0; // Remove the newline character
// Tokenize the input
arg_count = 0;
char *token = strtok(input, " ");
while (token != NULL) {
args[arg_count] = token;
arg_count++;
token = strtok(NULL, " ");
}
args[arg_count] = NULL; // Null-terminate the argument list
// Handle the "search" command
if (arg_count >= 4 && strcmp(args[0], "search") == 0) {
search_file(args[2], args[3], args[1]);
} else {
execute_command(args, arg_count);
}
}
return 0;
}
Comments
Post a Comment