C Programming

Call: getopt function usage

Most of us know how we can use arguments in our program, but if we start using many arguments and try to maintain the correct order and number of arguments, it will do a jumble puzzle for the user. To avoid such a hurdle, we will use different “options”. For example, “ls –l” here “–l” is an option. We can use multiple arguments and use them as options in multiple orders. We have also seen this with our GCC compiler in this article. Also, we can use a lot of options and can utilize them according to our needs.

Syntax:

Both ‘argc’ and ‘argv’ are the parameters for the count statement as accepted by the main()function. ‘optstring’ is the argument of a string that must recognize options characters. Any character tracked by a colon ‘:’ is considered an argument. ‘optind’ is the initialized variable that is considered an index for the next element in which it is in line next for processing.

Purpose of Using the getopt in C:

The function getopt() is built-in in C that is used to parse command-line arguments.

Return Value in getopt() function

  1. Getopt() will return ‘-1’ if there are no more options left to process.
  2. Getopt() will return ‘?’ if an option that is being processed is not recognizable.
  3. Getopt() returns “:” instead of ‘?’ if the user does not input any value for the argument.

If getopt() comes across an option character that is not in ‘optstring’, it will return the (‘?’) character as an output. If an argument is missing as an option, it should return a colon (‘:’) as an output. Getopt() will set the variable ‘optopt’ to the selected character that triggered the error in either case. Getopt() will correspondingly print an indicative message to stderr in the syntax defined for the ‘getopts’ utility if the variable ‘opterr’ is not set to 0 and the initial character of ‘optstring’ is not a colon.

The getopt() function doesn’t need to be re-entrant. Thread safety is not mandatory for a function that is not to be re-entrant.

Example for getopt() in C:

Let’s take a simple program that accepts users as -u and -g for the group. First of all, you need to include the header file for getopt() functionality.

#include <stdio.h>

#include <getopt.h>


Let’s set up the main function where we have ‘argc’ as integer and character array as ‘**argv’.  Now here, we will set up a few variables and set an integer name option_index = 0; because each of the arguments that we are going to provide will have an index number so that we can then iterate it through all of the arguments. We are setting or initializing it to 0 to stop the warning because we might be using a not initialized variable.

# Char *user_name = NULL;

Since we don’t have a string data type in C, we set up a character array for ‘-u’ to take the user name as an input and initiate it with a null value.

Now we will enter into a while loop, and it will allow us to read all of the arguments if any options have been set. As with conditions, we need our parentheses to enclose it with a true value which in our case is “option_index = getopt(argc,argv,”gu:”)”. We will use getopt() to look at our argument count as ‘argc’ and read from our array ‘argv’ to set the options. Likewise, here is an option “gu:” and we have put a colon after the flag “u”. The ‘:’ after the flag value indicates that it acquires an argument. It does not matter in what order you put the options, but it does matter that you put a colon after the options.

Now we will have a switch statement in our while loop, and we will examine the value stored in the index of the variable “option_index”. We are examining each item for each case.

We will first set the case where we set “user_name = optarg”. The options can be used to read the user we added as an input upon entering ‘u’. We also need to indicate that we are finished with this case, and we do that in C language by using ‘break’ after each case in the end.

Likewise, we use the second case where if the user input ‘g’, he will be indicated that he has selected the group, and we break from this statement as well.

Now in the last case, we are using it for any other options, which in our case can be any mistake. We can pick this up with ‘default:’ and we can go through and specify if the invalid option is identified or entered. We will display print statements with “incorrect option”.

We are also going to do a little diversity. We hope you haven’t seen before that is the return value. If we put the return value to 1, we will leave the main function. Our program will report an error which means we have run the program incorrectly, so we don’t want to return 0, so we leave the program at its point.

Now we have already closed all the blocks and made sure that we have usually got back to main brackets. The program normally returns 0 value to the main function. We have now successfully controlled failure operation by our program.

Let’s see if our program works; after typing the following code, we would like you to put this command in the command line. We used GCC and went straight into the source code ‘option_program.c’ and then used “-o” for options. After this, it’s going to be an argument, and here ‘simple’ is an output.

After executing our ‘gcc simple_option.c -o simple -Wall’ command successfully, now we go through and run with an incorrect option which is ‘-h’. Using “-h” as an option will give us an error because we have sent an incorrect option. We can also use both arguments together, getting the result accordingly.

Here we can see if we want to know how our last program was executed. If you type “echo $?”, and if it returns 0, it means the last program was executed successfully, and if it returns 1 as you can see in the above image, which means the last program execution is failed.

Conclusion:

This article aimed to give you a better and more clear understanding of the function getopt() so that you can improve your code readability and improve the reusability of the code. We have discussed a simple example with syntax. The article will help you easily get a very sound knowledge and understanding of how to use getopt() as a function. Different arguments as parameters have been discussed to make better use of the function.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.