我正在尝试实现一个列出文件和目录的“ls”命令。我已将传入参数数组设置为以下内容:
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 是否有任何问题?我该怎么办?
注意:我正在 OS X 上开发 Xcode。