Write a program to implement the toy 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.

count c filename: To print number of characters in the file.
count w filename: To print number of words in the file.

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

#define MAX_INPUT_SIZE 1024
#define MAX_ARG_SIZE 100

// Function to count characters in a file
void countCharacters(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        perror("Error opening file");
        return;
    }
    int ch, count = 0;
    while ((ch = fgetc(file)) != EOF) {
        count++;
    }
    fclose(file);
    printf("Number of characters: %d\n", count);
}

// Function to count words in a file
void countWords(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        perror("Error opening file");
        return;
    }
    char ch;
    int count = 0;
    int inWord = 0;

    while ((ch = fgetc(file)) != EOF) {
        if (ch == ' ' || ch == '\n' || ch == '\t') {
            if (inWord) {
                count++;
                inWord = 0;
            }
        } else {
            inWord = 1;
        }
    }
    if (inWord) {
        count++;
    }
    fclose(file);
    printf("Number of words: %d\n", count);
}

// Function to execute a command
void executeCommand(char *cmd) {
    char *args[MAX_ARG_SIZE];
    char *token = strtok(cmd, " \t\n");
    int i = 0;

    while (token != NULL) {
        args[i++] = token;
        token = strtok(NULL, " \t\n");
    }
    args[i] = NULL; // Null-terminate the argument list

    if (strcmp(args[0], "count") == 0) {
        if (i < 3) {
            printf("Usage: count c filename | count w filename\n");
            return;
        }
        if (strcmp(args[1], "c") == 0) {
            countCharacters(args[2]);
        } else if (strcmp(args[1], "w") == 0) {
            countWords(args[2]);
        } else {
            printf("Usage: count c filename | count w filename\n");
        }
    } else {
        pid_t pid = fork();
        if (pid == 0) {
            // Child process
            execvp(args[0], args);
            perror("execvp failed");
            exit(1);
        } else if (pid > 0) {
            // Parent process
            wait(NULL);
        } else {
            perror("fork failed");
        }
    }
}

int main() {
    char input[MAX_INPUT_SIZE];

    while (1) {
        printf("myshell$ ");
        if (fgets(input, sizeof(input), stdin) == NULL) {
            break; // Exit on EOF
        }
        // Remove the trailing newline character from the input
        input[strcspn(input, "\n")] = 0;

        if (strcmp(input, "exit") == 0) {
            break; // Exit the shell
        }

        executeCommand(input);
    }

    return 0;
}