2013-04-09 82 views
0

我試圖實現一個列出文件和目錄的'ls'命令。我已經設置了傳入參數數組爲以下:爲什麼程序沒有進入if語句時它應該

argv[0] = "./a.out" 
argv[1] = "-l" 
argv[2] = "test.c" 

這是我的代碼(假設main函數傳遞argcargv到功能I_AM_LS):

#include "ls.h" 

int I_AM_LS(int argc, char ** argv) 
{ 
    // 'INCLUDING_HIDDEN_FILE' indicates program performs ls including hidden files 
    // 'EXCLUDING_HIDDEN_FILE' indicates program performs ls excluding. 
    int  hidden_flag  = EXCLUDING_HIDDEN_FILE; 
    int  detail_flag  = SIMPLY;  // default option in ls. 
    // 'IN_DETAIL' indicates program performs ls with additional information. 
    // 'SIMPLY' indicates program performs ls without. 
    char option; 
    int i; 
    DIR * dp; 

    while ((option = getopt(argc, argv, "al")) != -1) 
    { 
     switch (option) 
     { 
      case 'a': 
       hidden_flag  = INCLUDING_HIDDEN_FILE; 
       break; 
      case 'l': 
       detail_flag  = IN_DETAIL; 
       break; 
      default: /* '?' */ 
       printf("invaild option.\n"); 
       return -1; 
     } 
    } 


if(argv[optind] != NULL && argv[optind + 1] != NULL) // multiple argument 
{ 
    ; // I have not finished the corresponding code yet. 
} 
else 
{ 
    if(argv[optind] == NULL) // case 1 
     I_REALLY_CALL_ls("./", hidden_flag, detail_flag); 
    else 
     I_REALLY_CALL_ls(argv[optind], hidden_flag, detail_flag); 
} 
    printf("optind %d %d\n", optind, argv[optind]); 
    return 0; 
} 
} 

int main(int argc, const char * argv[]) 
{ 
    I_AM_LS(argc, argv); 
    return 0; 
} 

初始解析循環後,程序不會進入if語句'argv [optind]!= NULL'。我們知道optind是2並且argv[optind]指向「test.c」,而不是NULL,在調試模式下看起來是相同的行爲。

將argv和argc傳遞給函數I_AM_LS會有什麼問題嗎?我該怎麼辦?

注:我工作的Xcode在OS X

回答

1
if(argv[optind] == NULL) // case 1 
    I_REALLY_CALL_ls("./", hidden_flag, detail_flag); 
else if(argv[optind] != NULL && argv[optind] != NULL) 
{ 
    ; 
} 

條件在此else ifargv[optind] != NULL,沒有很好的理由兩次評估。因此,如果第一個條件不成立,這一個呢,你什麼都不做(;)和

else if(argv[optind] != NULL) 
{ 
    // single non-option arguemnt. 
    I_REALLY_CALL_ls(argv[optind], hidden_flag, detail_flag); 
} 

不可達。

+0

這是勘誤。我的意圖是聲明'argv [optind]!= NULL && argv [optind + 1]'。我認爲這表示命令行由多個非選項參數組成。我編輯了代碼。你可以檢查我的代碼嗎?有什麼改進? – inherithandle 2013-04-09 15:20:12

相關問題