logoISU  

CS 456 - Systems Programming

Spring 2024

Displaying ./code/shellv4/shellbuiltins.c

#include "shell.h"

char *builtin_str[] = {
  "cd",
  "help",
  "curtime",
  "hello",
  "mycat",
  "exit"
};


int (*builtin_func[]) (char **) = {
  &shell_cd,
  &shell_help,
  &shell_curtime,
  &shell_hello,
  &shell_mycat,
  &shell_exit
};


int num_builtins() {

  return sizeof(builtin_str) / sizeof(char *);

}

int execute(char **args){
  
  int i;

  if (args[0] == NULL) {
    // An empty command was entered.
    return 1;
  }

  for (i = 0; i < num_builtins(); i++) {
    if (strcmp(args[0], builtin_str[i]) == 0) {
      return (*builtin_func[i])(args);
    }
  }

  return launch(args);  

}

int argcount(char **args){
  int argc = 0;

  for(int i = 0; args[i] != NULL; i++)
    argc++;

  return argc;

}

// shell builtins below
int shell_cd(char **args){

  if (args[1] == NULL) {
      fprintf(stderr, "shell: expected argument to \"cd\"\n");
    } else {
      if (chdir(args[1]) != 0) {
          perror("shell:");
      }
    }
  return 1;

}

int shell_help(char **args){

  printf("Current Builtins\n");

  for (int i = 0; i < num_builtins(); i++) {
    printf("  %s\n", builtin_str[i]);
  }

  return 1;

}

int shell_curtime(char **args){

  time_t curtime = time(NULL);

  char * time_str = ctime(&curtime);
  time_str[strlen(time_str)-1] ='\0';
  printf("%s\n", time_str);

  return 1;

}

int shell_hello(char **args){

  printf("Hello, world!\n");

  return 1;

}

int shell_mycat(char **args){

  if(argcount(args) < 2){
    printf("Usage: %s file\n",args[0]);
    return 1;
  }
  
  int rt;

  //open a file
  int fd = open(args[1], O_RDONLY);

  if(fd == -1){
    write(2, "open failed\n",12);
    return -1;
  }

  int size;
  struct stat st;
  fstat(fd, &st);
  size = st.st_size;

  char buf[size+1];

  rt = read(fd, buf, size);

  //printf("Number of bytes read: %d\n", rt);

  write(1, buf, rt);

  close(fd);

  return 1;
}



int shell_exit(char **args){
  return 0;
}