I'm currently programming a shell in C and I am stuck on the parsing function. At the moment I have a 'shell_readLine ()' function and a 'shell_split_line ()' function. I would like to improve the splitLine function so that it takes into account redirects such as: '|', '<' or '>'. Currently, only spaces serve as delimiters. I do not know where to start.
shell_readLine fonction :
char *shell_readLine(void)
{
int buffsize = SHELL_RL_BUFFSIZE;
int position = 0;
char *buffer = malloc(sizeof(char) * buffsize);
int c;
if(!buffer) {
fprintf(stderr, "shell: allocation error\n");
exit(EXIT_FAILURE);
}
while(1) {
// Read a character
c = getchar();
// If EOF, replace with null and return
if(c == EOF || c == '\n') {
buffer[position] = '\0';
return buffer;
} else {
buffer[position] = c;
}
position++;
// Check if we have exceeded the buffer and reallocate if necessary
if(position >= buffsize) {
buffsize += SHELL_RL_BUFFSIZE;
buffer = realloc(buffer, buffsize);
if(!buffer) {
fprintf(stderr, "shell: allocation error\n");
exit(EXIT_FAILURE);
}
}
}
}
And my shell_split_line fonction :
/*
* Does not allow quoting or backslash escaping in command line args
*/
char **shell_split_line(char *line) {
int buffsize = SHELL_TOK_BUFFSIZE, position = 0;
char **tokens = malloc(buffsize * sizeof(char *));
char *token;
if(!tokens) {
fprintf(stderr, "shell: allocation error\n");
exit(EXIT_FAILURE);
}
token = strtok(line, SHELL_TOK_DELIM);
while(token != NULL) {
tokens[position] = token;
position++;
if(position >= buffsize) {
buffsize += SHELL_TOK_BUFFSIZE;
tokens = realloc(tokens, buffsize * sizeof(char *));
if(!tokens) {
fprintf(stderr, "shell: allocation error\n");
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, SHELL_TOK_DELIM);
}
tokens[position] = NULL;
return tokens;
}
Thanks in advance for your advices and ideas. I do not really know where to start and even how to make this. It's my first shell ever and i'm not a pro of C language.