Getopt function usage and getopt function usage

Source: Internet
Author: User

Getopt function usage and getopt function usage

Linux provides a function to parse command line parameters.

#include <unistd.h>       int getopt(int argc, char * const argv[],                  const char *optstring);       extern char *optarg;       extern int optind, opterr, optopt;

Using this function, we can run the following command:

./a.out -n -t 100

N does not require a parameter. t requires a value as a parameter.

The Code is as follows:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <errno.h>#define ERR_EXIT(m) \    do { \        perror(m);\        exit(EXIT_FAILURE);\    }while(0)int main(int argc, char *argv[]){    int opt;    while(1)    {        opt = getopt(argc, argv, "nt:");        if(opt == '?')            exit(EXIT_FAILURE);        if(opt == -1)            break;        switch(opt)        {            case 'n':                printf("AAAAAAAA\n");                break;            case 't':                printf("BBBBBBBB\n");                int n = atoi(optarg);                printf("n = %d\n", n);        }    }    return 0;}

If an invalid parameter is input, getopt returns '? ', When the resolution is complete,-1 is returned.

If a parameter is required, use optarg to obtain it. This is a global variable.

Note that the third parameter "nt:" Of getopt indicates that n and t are available, and t is followed by a colon, indicating that t requires additional parameters.

The running result is as follows:

5:30:22 wing@ubuntu msg ./getopt_test -nAAAAAAAA5:30:26 wing@ubuntu msg ./getopt_test -t ./getopt_test: option requires an argument -- 't'5:30:31 wing@ubuntu msg ./getopt_test -t 100                                           1 ↵BBBBBBBBn = 100

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.