custom-unix-shell / wish-v1.c
wish-v1.c
Raw
//Add your code here
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<ctype.h>

#define MAXCOM 1000 // max number of letters to be supported
#define MAXLIST 100 // max number of commands to be supported

// function to prompt std input
void takeStdInput()
{
    char *line = NULL; // buffer to store each line read
    size_t len = 0; // length of the line read
    ssize_t read; // number of characters read by getline
    
    while(1) {
        char args[30][30]; // store an array of arguments
        int argsCounter = 0; // number of arguments

        // print shell prompt
        printf("wish> ");

        // take input
        while ((read = getline(&line, &len, stdin)) != -1) {
            // remove newline character from command string
            if (line[strlen(line) - 1] == '\n') {
                line[strlen(line) - 1] = '\0';
            }

            char *found = NULL;
            while ( (found = strsep(&line," ")) != NULL ) {
                // Skip over any leading space characters
                while (isspace(*found)) {
                    found++;
                }
                // Skip empty tokens if met
                if (*found == '\0') {
                    continue;
                }
                sprintf(args[argsCounter], "%s", found);
                argsCounter++;
                free(found);
            }
            break;
        }
        // check for 'exit' argument
        for (int i=0; i<argsCounter; i++) {
            if (strcmp(args[i],"exit") == 0) {
                free(line);
                exit(0);
            }
        }
        
    }
}

// function to execute given batch file
void takeBatchInput(char *inputFile) 
{
    FILE * fp = fopen(inputFile, "r");
    if (fp == NULL) {
        char error_message[30] = "An error has occurred\n";
        write(STDERR_FILENO, error_message, strlen(error_message));
    }
}

int main(int argc, char *argv[]) 
{    
    // If given more than one command-line argument -> error
    if (argc > 2) {
        char error_message[30] = "An error has occurred\n";
        write(STDERR_FILENO, error_message, strlen(error_message));
    }
    // If given one argument -> prompt input
    else if (argc == 1) {
        takeStdInput();
    }
    // If given a batch file -> execute commands in file
    else {
        takeBatchInput(argv[1]);
    }

    return 0;
  
}