Aladin Flex-Tox
Aladin Flex-Tox

Reputation: 49

My shell has to interpret the double quote

I have to write a shell that can interpret double quotes. I've written a basic shell.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
  int main ()
  {
    int i;
char * ligne;
char *tokens[100];
ligne=(char*)malloc(300);
printf("$ ");
fgets(ligne,256,stdin);
while (strcmp(ligne,"exit\n"))
{   i=0;
    tokens[i]=strtok(ligne," \n");
    while (tokens[i] != NULL) tokens[++i]=strtok(NULL," \n");
    if (fork()==0)
    {   execvp(tokens[0],tokens);
        printf("Commande invalide\n");
        exit(1);
    }
    wait(0);
    printf("$ ");
    fgets(ligne,256,stdin);
}
exit(0);
}

In a linux shell: When you enter a command like

 $ echo "`a     b`"

The shell interprets spaces and therefore

a     b

is taken as a file.

I do not see how to remove the double quotes and keep the spaces. Thank you.

Upvotes: 1

Views: 150

Answers (1)

Armali
Armali

Reputation: 19375

strtokis not suited for that. Replace

    tokens[i]=strtok(ligne," \n");
    while (tokens[i] != NULL) tokens[++i]=strtok(NULL," \n");

e. g. with

    char quot = 0, *cp;
    for (cp = ligne; tokens[i] = cp += strspn(cp, " \n"), *cp; ++i)
    {
        do if (*cp == '"') quot ^= 1, memmove(cp, cp+1, strlen(cp));
         while (cp += strcspn(cp, quot ? "\"" : " \n\""), *cp == '\"');
        if (*cp) *cp++ = '\0';
    }
    tokens[i] = NULL;
    if (quot) puts("unmatched quotation mark");
    else

.

Upvotes: 1

Related Questions