2012-03-28 65 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