I'm on the rails again as a side side project. I started to parse arguments given from a command line to train my UNIX programming skills. That'll come quite handy for the minishell project i plan to do.
Here's the code atm for anyone who wants to dig into (only for PC as test, I haven't ported it to FiXOS, but that should be easy) :
#define _GNU_SOURCE
#include <unistd.h>
#include <string.h>
#define BUFFER_LENGTH 128
#define COMMAND_LIST_SIZE 8
#define COMMAND_SIZE 32
void next_command(char* current_command, int* current_command_index, int* command_index) {
current_command[*current_command_index] = '\0';
*current_command_index = 0;
*command_index += 1;
}
void parse_command(char* buffer, char command_list[COMMAND_LIST_SIZE][COMMAND_SIZE], int buffer_index) {
int command_index = 0;
int current_command_index = 0;
char in_quotes = 0;
char in_double_quotes = 0;
char c;
int i;
for(i = 0; i < buffer_index; i++) {
char *current_command = command_list[command_index];
c = buffer[i];
if(in_quotes) {
if(c == '\'') {
in_quotes = 0;
}
else {
current_command[current_command_index] = c;
current_command_index++;
}
}
else if(in_double_quotes) {
if(c == '"') {
in_double_quotes = 0;
}
else {
current_command[current_command_index] = c;
current_command_index++;
}
}
else {
if(c == '"' || c == '\'') {
if(current_command_index > 0) {
next_command(current_command, ¤t_command_index, &command_index);
}
if(c == '"')
in_double_quotes = 1;
else
in_quotes = 1;
}
else if(c == ' ' && current_command_index > 0) {
next_command(current_command, ¤t_command_index, &command_index);
}
else {
current_command[current_command_index] = c;
current_command_index++;
}
}
}
next_command(command_list[command_index], ¤t_command_index, &command_index);
for(i = 0; i < command_index; i++) {
write(1, "=>{", 3);
write(1, &command_list[i], strlen(command_list[i]));
write(1, "}\n", 2);
}
}
int main()
{
char c;
int buffer_index = 0;
char buffer[BUFFER_LENGTH + 1];
char command_list[COMMAND_LIST_SIZE][COMMAND_SIZE];
while(1) {
read(0, &c, 1);
if(c == '\n') {
// TODO : manage command
parse_command(buffer, command_list, buffer_index);
buffer_index = 0;
}
else if(buffer_index <= BUFFER_LENGTH) {
buffer[buffer_index++] = c;
}
}
return 0;
}