2012-03-28 30 views
1

我必须编写一个可以解释双引号的shell。 我写了一个基本的shell。我的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); 
} 

在Linux Shell:当你输入如下命令

$ echo "`a  b`" 

Shell解释的空间,因此

a  b 

被当作一个文件。

我不明白如何删除双引号并保留空格。 谢谢。

+0

'使用单引号保留空间'。并且请让你的问题更清楚(如你期望的输出),所以我可以提供你正在寻找的确切答案。 – ganesshkumar 2012-03-29 11:21:27

回答

1

strtok不适合那个。替换

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

e。 G。与

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