Write a C program to implement the 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
typeline +n filename:- To print first n lines in the file.
typeline -a  filename:- To print all lines in the file.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

// Function to print the first n lines of a file
void print_first_n_lines(const char *filename, int n) {
    FILE *file = fopen(filename, "r");
    if (!file) {
        perror("fopen");
        return;
    }

    char line[256];
    int line_count = 0;

    while (fgets(line, sizeof(line), file) && line_count < n) {
        printf("%s", line);
        line_count++;
    }

    fclose(file);
}

// Function to print all lines of a file
void print_all_lines(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (!file) {
        perror("fopen");
        return;
    }

    char line[256];
    while (fgets(line, sizeof(line), file)) {
        printf("%s", line);
    }

    fclose(file);
}

int main() {
    char input[1024];

    while (1) {
        // Display the command prompt
        printf("myshell$ ");
        fflush(stdout);

        // Read the input command
        if (!fgets(input, sizeof(input), stdin)) {
            perror("fgets");
            exit(EXIT_FAILURE);
        }

        // Remove newline character from input
        input[strcspn(input, "\n")] = '\0';

        // Tokenize the command line
        char *token = strtok(input, " ");
        if (!token) continue; // No command entered

        // Check for 'typeline' command
        if (strcmp(token, "typeline") == 0) {
            token = strtok(NULL, " ");
            if (!token) continue; // Missing option

            char *option = token;
            token = strtok(NULL, " ");
            if (!token) continue; // Missing filename

            char *filename = token;

            // Fork and exec to run the typeline command
            pid_t pid = fork();
            if (pid == 0) {
                // Child process
                if (strcmp(option, "+n") == 0) {
                    int n = atoi(strtok(NULL, " "));
                    print_first_n_lines(filename, n);
                } else if (strcmp(option, "-a") == 0) {
                    print_all_lines(filename);
                } else {
                    printf("Invalid option. Use +n for first n lines or -a for all lines.\n");
                }
                exit(EXIT_SUCCESS);
            } else if (pid > 0) {
                // Parent process
                wait(NULL); // Wait for child process to finish
            } else {
                perror("fork");
            }
        } else {
            printf("Invalid command. Use 'typeline' followed by option and filename.\n");
        }
    }

    return 0;
}