为什么程序不应该进入if语句

时间:2013-04-09 14:26:06

标签: c system-calls

我正在尝试实现一个列出文件和目录的'ls'命令。我已将传入的参数数组设置为以下内容:

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是否有任何问题?我该怎么办?

注意:我正在使用OS X上的Xcode。

1 个答案:

答案 0 :(得分:1)

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

else if中的条件为argv[optind] != NULL,无理由评估两次。因此,如果第一个条件不成立,那么这个条件没有(;)和

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

无法访问。