0
我試圖實現一個列出文件和目錄的'ls'命令。我已經設置了傳入參數數組爲以下:爲什麼程序沒有進入if語句時它應該
argv[0] = "./a.out"
argv[1] = "-l"
argv[2] = "test.c"
這是我的代碼(假設main
函數傳遞argc
和argv
到功能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
這是勘誤。我的意圖是聲明'argv [optind]!= NULL && argv [optind + 1]'。我認爲這表示命令行由多個非選項參數組成。我編輯了代碼。你可以檢查我的代碼嗎?有什麼改進? – inherithandle 2013-04-09 15:20:12