Umar Gul
Umar Gul

Reputation: 7

Compare string literal command line parameters in C

I need my program to run this way ./src c 2345 or ./src s 345, whereby the first character hs to be either c or s and second an integer. The program should throw an usage error if there's any less parameters and also any charcter other than c or s. Here's my code

int main(int argc, char **argv) {

    int num_of_connections = 0, client_sockfd;
    int max_sockfd, master_socket;

    fd_set socket_collection, read_collection;

    // Check validity of the user input
    if(argc < 3) {
        if((strcmp(argv[2], "s") != 0) || (strcmp(argv[2], "c") != 0)){
            fprintf(stderr, "Usage: ./src <s/c> <port>\n");
            exit(EXIT_FAILURE);
        }

    }

When I enter one argument I get a segmentation fault. Also it doesnt identify the C or S parameter. Any help will be appreciated.

Upvotes: 1

Views: 719

Answers (2)

Kijewski
Kijewski

Reputation: 26022

if(argc < 3) { does not make sense if you want exactly two parameters. In the inner if block you are confusion || (logical or) with && (logical and).

In your invocation example ./src s 345 the character is the first argument, so probably argv[2] should read argv[1].

if ((argc != 3) || ((strcmp(argv[1], "s") != 0) &&
                    (strcmp(argv[1], "c") != 0))) {
    fprintf(…);
    return EXIT_FAILURE;
}

Note: all parentheses in this if (…) condition are optional, because of C's operator precedence. I put them for readability.

Upvotes: 1

Notice that main has a very specific convention: the argv array has argc+1 members, with the last being NULL and the others being non-null distinct pointers to zero-terminated strings.

So if argc is 1 (e.g. if your run ./src alone) or 2, argv[2] is NULL and you cannot pass it to  strcmp

You can call strcmp(argv[2],"s") only when argc>=3

BTW, I would suggest to use getopt(3) or preferably (on Linux only) getopt_long and to accept the --help and --version arguments, per GNU conventions.

Also, compile with all warnings and debug info (gcc -Wall -g) and use the gdb debugger. It would be faster for you to use gdb than to ask here and wait for replies.

Upvotes: 1

Related Questions