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 ‘typeline’ as myshell$ typeline n filename: It will display first n lines of the file. myshell$ typeline -n filename: It will display last n lines of the file. myshell$ typeline a filename: It will display all the lines of the 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 typeline(char *option, char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("fopen");
return;
}
char line[MAX_INPUT_SIZE];
int n = 0;
int line_count = 0;
if (option[0] == '-') {
// Display last n lines
n = atoi(option + 1);
if (n <= 0) {
fclose(file);
return;
}
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
while (file_size > 0 && line_count < n) {
fseek(file, --file_size, SEEK_SET);
if (fgetc(file) == '\n') {
line_count++;
}
}
} else if (strcmp(option, "a") == 0) {
// Display all lines
} else {
// Display first n lines
n = atoi(option);
if (n <= 0) {
fclose(file);
return;
}
}
line_count = 0;
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
line_count++;
if (n > 0 && line_count >= n) {
break;
}
}
fclose(file);
}
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 "typeline" command
if (arg_count >= 3 && strcmp(args[0], "typeline") == 0) {
typeline(args[1], args[2]);
} else {
execute_command(args, arg_count);
}
}
return 0;
}

Comments
Post a Comment