Skip to content
Snippets Groups Projects
Select Git revision
  • 7c20e82ea868372d93cdb723326af8aca4d3e567
  • main default
2 results

stringfun

Blame
  • dshlib.c 2.89 KiB
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    #include "dshlib.h"
    
    int numInstanceOf(char *str, const char c) {
        int count = 0;
        while (*str != '\0') {
    		if (*str == c) count++;
        	str++;
        }
    
        return count;
    }
    
    /*
     *  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)
    strcat(command.args, inner_token); *                             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)
    {
    	if (numInstanceOf(cmd_line, PIPE_CHAR) > CMD_MAX-1) return ERR_TOO_MANY_COMMANDS;
    	
    	if ((int)strlen(cmd_line) > SH_CMD_MAX) return ERR_CMD_OR_ARGS_TOO_BIG;
    	
    	clist->num = 0;
    
        char *outer_saveptr = NULL;
        char *inner_saveptr = NULL;
        char *outer_token = strtok_r(cmd_line, PIPE_STRING, &outer_saveptr);
        
        while (outer_token != NULL) {
            if (clist->num > CMD_MAX) return ERR_TOO_MANY_COMMANDS;
    
            command_t command;
            memset(&command, 0, sizeof(command_t));
    
    
    
            char *inner_token = strtok_r(outer_token, SPACE_STRING, &inner_saveptr);
            
    		if (inner_token == NULL) {
    			outer_token = strtok_r(NULL, PIPE_STRING, &outer_saveptr);
    			continue;
    		}