2016-10-08 33 views
0

這裏是我想要做的: 用戶需要在提示符下輸入命令,程序將評估命令以知道該怎麼做。 如果未找到該命令,那麼shell將返回錯誤「未找到命令!」。 如果用戶輸入命令EXIT,程序應該退出。 爲簡單起見,爲了避免用戶輸入時沒有輸入任何內容,我們將假設用戶總是輸入一些內容。 不會使用空字符串。我應該將它與這裏的循環是我想做的事:如何編寫一個用於評估shell命令的c程序

例子:

shell.exe

殼牌>測試

命令沒有找到!

Shell> test2

未找到命令!

殼牌>出口

>

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main() 
{ 
    char command[20]; 

    while (command != "exit") { 

     //check with an if statement for valid commands 
     printf("Enter a command:\n"); 
     gets(command); 
    } 

    if (command == "exit") { 
     //program should exit 
    } 

    return 0; 
} 
+3

您無法將c字符串與'=='進行比較。 – tkausl

+1

我知道我只是不知道該怎麼做 –

+2

您需要使用c庫函數之一來比較字符串。 https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm – drescherjm

回答

-1

選其一popen()system()。 Popen爲I/O提供了一個處理程序,而系統給出了一個狗屎,但是您仍然可以在命令行上重定向到一個管道(「<」和「>」),並從那裏讀取和寫入I/O。

+0

我'我不太確定,但是如果你使用system()寫入(0,&datatowrite,quantofbytestowrite)作爲I/O寫入,那麼這可能是有效的。 –

-1

如果你使用while循環,你應該給命令數組一個字符串值,這樣可以在循環條件下進行檢查。

char exit[4] = "exit"; 
gets(command); 


if (strcmp(command,exit) == 0) 
{ 
    //Exit programm 
} 
while (strcmp(command,exit)) != 0) 
{ 
    printf("Command not found!"\n Enter a command \n); 
    gets(command); 
    if (strcmp(command,exit) == 0) 
    { 
     //Exit programm 
    } 
}