dimanche 18 novembre 2018

True and false in C in if statement with getopt()

I have a hard time in understatanding how true and false works with "if statement" when I am using argv & getopt.

This is the simple code:

#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]); 
}

Usage:

./a.out foo

Output:

Without option -l or -i but with other argument 
argv[1] is foo

It's good so far. Now let me check if it works when argv[1] is "-l":

Usage:

./a.out -l

Output:

./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

Getopt works fine, but second information occurs even if argv[1] is -l and I set in "if" statement that (argv[1] != "-l"). Why it works like that? I have no clue.

Thanks for any answer. B.

Aucun commentaire:

Enregistrer un commentaire