dish/line.c

55 lines
1.2 KiB
C
Raw Normal View History

2022-09-18 06:46:23 +00:00
/*
* @Author: 1ridic
* @Date: 2022-09-18 14:14:05
* @Last Modified by: 1ridic
* @Last Modified time: 2022-09-18 14:14:05
2022-09-18 06:46:23 +00:00
*/
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "line.h"
char **splitLine(char *line) {
int bufsize = LINE_BUF_SIZE, position = 0;
char **tokens = malloc(bufsize * sizeof(char *));
char *token;
if (!tokens) {
fprintf(stderr, "dish: allocation error");
exit(EXIT_FAILURE);
}
/* get sub string
*" \t\r\n\a" is a set of delimiters,
* which stands for space, tab, carriage, newline, and alert.
*/
token = strtok(line, " \t\r\n\a");
while (token != NULL) {
tokens[position] = token;
2022-09-18 05:14:30 +00:00
#ifdef DEBUG
fprintf(stdout, "debug: tokens[%d] = %s\n", position, tokens[position]);
#endif
position++;
/* if the buffer is full, reallocate */
if (position >= bufsize) {
bufsize += LINE_BUF_SIZE;
tokens = realloc(tokens, bufsize);
if (!tokens) {
fprintf(stderr, "dish: allocation error\n");
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, " \t\r\n\a");
}
/* set the last element to NULL */
tokens[position] = NULL;
return tokens;
}