2011-10-24 17 views
1

我對C來說相當陌生,而且似乎碰壁了。我是否通過這個參數來改變工作目錄,只要有人在cd目錄中正確輸入?如果我沒有包含一個目錄,它默認報告當前的工作目錄,但當我給出一個參數時,我似乎無法讓目錄改變。使用chdir改變c中的工作目錄

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

#define MAX_BUFFER 1024      // max line buffer 
#define MAX_ARGS 64       // max # args 
#define SEPARATORS " \t\n"      // token sparators 

extern char **environ; 
/*******************************************************************/ 

int main (int argc, char ** argv) 
{ 
char linebuf[MAX_BUFFER];     // line buffer 
char cmndbuf[MAX_BUFFER];     // command buffer 
char * args[MAX_ARGS];      // pointers to arg strings 
char ** arg;        // working pointer thru args 
char * prompt = "==>" ;     // shell prompt 

// keep reading input until "quit" command or eof of redirected input 

while (!feof(stdin)) { 

// get command line from input 


    fputs (prompt, stdout);    // write prompt 
    fflush(stdout); 
    if (fgets(linebuf, MAX_BUFFER, stdin)) { // read a line 

// tokenize the input into args array 

     arg = args; 
     *arg++ = strtok(linebuf,SEPARATORS); // tokenize input 
     while ((*arg++ = strtok(NULL,SEPARATORS))); 
              // last entry will be NULL 

     if (args[0]) {      // if there's anything there 

      cmndbuf[0] = 0;    // set zero-length command string 

// check for internal/external command 

      if (!strcmp(args[0],"clr")) { // "clr" command 
       strcpy(cmndbuf, "clear"); 
      } else 
      if (!strcmp(args[0],"cd")) 
      { 
       int ret; 
       if (!args[1]) 
        strcpy(cmndbuf, "pwd"); 
       ret = chdir(args[1]); 
       strcpy(cmndbuf, "pwd"); 


      }else 
      if (!strcmp(args[0],"dir")) { // "dir" command 
       strcpy(cmndbuf, "ls -al "); 
       if (!args[1]) 
        args[1] = ".";   // if no arg set current directory 
       strcat(cmndbuf, args[1]); 
      } else 
      if (!strcmp(args[0],"environ")) { // "environ" command 
       char ** envstr = environ; 
       while (*envstr) {   // print out environment 
        printf("%s\n",*envstr); 
        envstr++; 
       }       // (no entry in cmndbuf) 
      } else 
      if (!strcmp(args[0],"quit")) { // "quit" command 
       break; 
      } else {       // pass command on to OS shell 
       int i = 1; 
       strcpy(cmndbuf, args[0]); 
       while (args[i]) { 
        strcat(cmndbuf, " "); 
        strcat(cmndbuf, args[i++]); 
       } 
      } 

// pass any command onto OS 

      if (cmndbuf[0]) 
       system(cmndbuf); 
     } 
    } 
} 
return 0; 
} 

謝謝。

+0

請勿使用'feof(stdin)'來控制循環的終止。首先,'feof()'會在輸入錯誤後返回false,這會導致無限循環。當沒有什麼可讀的時候,fgets()返回一個空指針;用它來終止你的循環。 –

+0

http://stackoverflow.com/questions/5431941/in-c-is-while-feof-always-wrong –

回答

2

我剛編譯並運行你的程序,它工作。

$ gcc c.c -o c 
$ ./c 
==>cd 
/home/kst 
==>cd /tmp 
/tmp 
==>cd 
/tmp 
==>cd/  
/
==>quit 
$ 
+0

謝謝。我重新啓動了我的環境,它工作。我很感激幫助。 – Ryan

+2

但是你忽略了'chdir()'和'system()'的任何可能的錯誤。 –