带有getopt()的if语句中的C中的true和false

Blo*_*ary 1 c unix if-statement getopts argv

当我使用argv和getopt时,我很难理解"if语句"是如何真实和错误的.

这是简单的代码:

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

int main(int argc, char *argv[]) {
        int opt;

while ((opt = getopt (argc, argv, "i:l:")) != -1)
        switch (opt) {
        case 'i':
                printf("This is option i");           
                break;
        case 'l':
                printf("This is option l");
                break;
        default:
                fprintf(stderr,"Usage: %s here goes usage\n",argv[0]); 
    }

if (argc == 1) {
    printf("Without options");
}

if ((argc == 2) && (argv[1] != "-l") || (argv[1] != "-i")) {
    printf("Without option -l or -i but with other argument \n");
    printf("argv[1] is %s\n", argv[1]); 
}
Run Code Online (Sandbox Code Playgroud)

用法:

./a.out foo
Run Code Online (Sandbox Code Playgroud)

输出:

Without option -l or -i but with other argument 
argv[1] is foo
Run Code Online (Sandbox Code Playgroud)

到目前为止一切都很好.现在让我检查一下当argv [1]是"-l"时它是否有效:

用法:

./a.out -l
Run Code Online (Sandbox Code Playgroud)

输出:

./a.out: option requires an argument -- 'l'
Usage: ./a.out here goes usage
Without option -l or -i but with other argument 
argv[1] is -l
Run Code Online (Sandbox Code Playgroud)

Getopt工作正常,但是即使argv [1]是-l而且我在"if"语句中设置了(argv [1]!=" - l"),也会出现第二个信息.它为什么这样?我没有线索.

谢谢你的回答.B.

pax*_*blo 6

千万不能使用:

argv[1] != "-l"
Run Code Online (Sandbox Code Playgroud)

为了比较C (a)中的字符串,这比较了(b)的两个数组的地址而不是这两个字符串的内容.Instaed,你应该使用:char

strcmp(argv[1], "-l") == 0
Run Code Online (Sandbox Code Playgroud)

(a)这是C++字符串中修复的东西之一,那里的相等运算符比较字符串的内容.

(b)有时似乎可以使用类似的东西,"xyzzy" == "xyzzy"但这只是因为编译器被允许(但不是必需)将相同的字符串常量折叠在一起(因此它们占用的空间更少).当其中一个字符串不是常量时(例如当它在命令行上传递时),通常是不可能的.