/* Parses input command and puts args into arg array. Returns number of arguments on success, -1 on failure. */ static int parse_command(const char *input, char (*args)[MAX_COMMAND_LENGTH]) { char *cmd = strdup(input); if (cmd == NULL) { exit(EXIT_FAILURE); } int num_args = 0; int i = 0; /* index of last char in an argument */ /* characters wrapped in double quotes count as one arg */ while (num_args < MAX_NUM_ARGS) { int qt_ofst = 0; /* set to 1 to offset index for quote char at end of arg */ if (*cmd == '\"') { qt_ofst = 1; i = char_find(1, cmd, '\"'); if (cmd[i] == '\0') { free(cmd); return -1; } } else { i = char_find(0, cmd, ' '); } memcpy(args[num_args], cmd, i + qt_ofst); args[num_args++][i + qt_ofst] = '\0'; if (cmd[i] == '\0') { /* no more args */ break; } char tmp[MAX_COMMAND_LENGTH]; snprintf(tmp, sizeof(tmp), "%s", &cmd[i + 1]); strcpy(cmd, tmp); /* tmp will always fit inside cmd */ } free(cmd); return num_args; }
/* Parses input command and puts args into arg array. Returns number of arguments on success, -1 on failure. */ static int parse_command(WINDOW *w, ToxWindow *self, const char *input, char (*args)[MAX_STR_SIZE]) { char *cmd = strdup(input); if (cmd == NULL) exit_toxic_err("failed in parse_command", FATALERR_MEMORY); int num_args = 0; int i = 0; /* index of last char in an argument */ /* characters wrapped in double quotes count as one arg */ while (num_args < MAX_NUM_ARGS) { int qt_ofst = 0; /* set to 1 to offset index for quote char at end of arg */ if (*cmd == '\"') { qt_ofst = 1; i = char_find(1, cmd, '\"'); if (cmd[i] == '\0') { const char *errmsg = "Invalid argument. Did you forget a closing \"?"; line_info_add(self, NULL, NULL, NULL, SYS_MSG, 0, 0, errmsg); free(cmd); return -1; } } else { i = char_find(0, cmd, ' '); } memcpy(args[num_args], cmd, i + qt_ofst); args[num_args++][i + qt_ofst] = '\0'; if (cmd[i] == '\0') /* no more args */ break; char tmp[MAX_STR_SIZE]; snprintf(tmp, sizeof(tmp), "%s", &cmd[i + 1]); strcpy(cmd, tmp); /* tmp will always fit inside cmd */ } free(cmd); return num_args; }