Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do these codes do?

Tags:

c

I saw this source code in a book:

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


int main(int argc, char *argv[])
{
    char *delivery = "";
    int thick = 0;
    int count = 0;
    char ch;

    while ((ch = getopt(argc, argv, "d: t")) != EOF)
        switch(ch)
        {
            case 'd':
                delivery = optarg;
                break;

            case 't':
                thick = 1;
                break;

            default:
                fprintf(stderr, "Unknown option: '%s'\n", optarg);
                return 1;
        }

        argc -= optind;
        argv += optind;

        if (thick)
            puts("Thick Crust.");

        if (delivery[0])
            printf("To be deliverd %s\n", delivery);

        puts("Ingredients: ");

        for (count = 0; count < argc; count++)
            puts(argv[count]);

    return 0;
}

I can understand the entire source except:

argc -= optind;
argv += optind;

I know what is argc and argv, but what happen them in these two lines, what is "optind" Explain me.

Thank you.

like image 338
0xEDD1E Avatar asked Aug 16 '12 12:08

0xEDD1E


People also ask

What can codes do?

Coding creates a set of instructions for computers to follow. These instructions determine what actions a computer can and cannot take. Coding allows programmers to build programs, such as websites and apps. Computer programmers can also tell computers how to process data in better, faster ways.

What is a code and how does it work?

Coding is the process of using a programming language to get a computer to behave how you want it to. In Python, every line of code tells the computer to do something, and a document full of lines of code is called a script. Each script is designed to carry out a job.

What are codes in computer?

In computer programming, computer code refers to the set of instructions, or a system of rules, written in a particular programming language (i.e., the source code). It is also the term used for the source code after it has been processed by a compiler and made ready to run on the computer (i.e., the object code).

Why is code used?

In computers, coding is done to understand what is expected for it to be done. The benefits of learning coding are many, and the most beneficial ones. Coding helps you build applications, put them over servers and use them so that multiple users can use them and get the benefits.


1 Answers

The getopt library provides several function to help parsing the command line arguments.

When you call getopt it "eats" a variable number of arguments (depending on the type of command line option); the number of arguments "eaten" is indicated in the optind global variable.

Your code adjusts argv and argc using optind to jump the arguments just consumed.

like image 119
Matteo Italia Avatar answered Sep 19 '22 14:09

Matteo Italia