Select Git revision
dshlib.c 3.30 KiB
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "dshlib.h"
/*
* build_cmd_list
* cmd_line: the command line from the user
* clist *: pointer to clist structure to be populated
*
* This function builds the command_list_t structure passed by the caller
* It does this by first splitting the cmd_line into commands by spltting
* the string based on any pipe characters '|'. It then traverses each
* command. For each command (a substring of cmd_line), it then parses
* that command by taking the first token as the executable name, and
* then the remaining tokens as the arguments.
*
* NOTE your implementation should be able to handle properly removing
* leading and trailing spaces!
*
* errors returned:
*
* OK: No Error
* ERR_TOO_MANY_COMMANDS: There is a limit of CMD_MAX (see dshlib.h)
* commands.
* ERR_CMD_OR_ARGS_TOO_BIG: One of the commands provided by the user
* was larger than allowed, either the
* executable name, or the arg string.
*
* Standard Library Functions You Might Want To Consider Using
* memset(), strcmp(), strcpy(), strtok(), strlen(), strchr()
*/
int build_cmd_list(char *cmd_line, command_list_t *clist)
{
char *pointer = cmd_line;
char* pipe = strchr(pointer, PIPE_CHAR);
clist->num = 0;
command_t new_command;
void make_command(command_t new_command, char *pointer, command_list_t *clist, size_t sub_length){
while (*pointer == ' '){
pointer++;
}
char *space = strchr(pointer, SPACE_CHAR);
if (space==NULL){
memset(new_command.exe, 0, sizeof(new_command.exe));
size_t exe_length = strlen(pointer);
strncpy(new_command.exe, pointer, exe_length);
memset(new_command.args, 0, sizeof(new_command.args));
new_command.args[0] = '\0';
clist->commands[clist->num] = new_command;
clist->num = clist->num+1;
} else{
while (*space==' '){
space++;
}
size_t exe_length = space - pointer;
memset(new_command.exe, 0, sizeof(new_command.exe));
strncpy(new_command.exe, pointer, exe_length);
new_command.exe[exe_length] = '\0';
size_t arg_length = pointer + sub_length - space;
memset(new_command.args, 0, sizeof(new_command.args)); strncpy(new_command.args, space, arg_length);
new_command.args[arg_length] = '\0';
clist->commands[clist->num] = new_command;
clist-> num = clist->num + 1;
}
}
while(pointer != NULL){
pipe = strchr(pointer, PIPE_CHAR);
if (pipe==NULL){
size_t command_length = strlen(pointer);
make_command(new_command, pointer, clist, command_length);
pointer = pipe;
} else{
size_t sub_length = pipe - pointer;
char sub_string[sub_length + 1];
strncpy(sub_string, pointer, sub_length);
sub_string[sub_length] = '\0';
make_command(new_command, sub_string, clist, sub_length);
pointer = pipe + 1;
}
}
return OK;
}