The getopt() function is a builtin function in C and is used to parse command line arguments.
getopt(int argc, char *const argv, const char *optstring) optstring is simply a list of characters, each representing a single character option.
Return Value: The getopt() function returns different values:
- If the option takes a value, that value is pointer to the external variable optarg.
- ‘-1’ if there are no more options to process.
- ‘?’ when there is an unrecognized option and it stores into external variable optopt.
- If an option requires a value (such as -f in our example) and no value is given, getopt normally returns ?.
By placing a colon as the first character of the options string, getopt returns: instead of ? when no value is given.
Generally, the getopt() function is called from inside of a loop’s conditional statement. The loop terminates when the getopt() function returns -1. A switch statement is then executed with the value returned by getopt() function.
A second loop is used to process the remaining extra arguments that cannot be processed in the first loop.
Below program illustrate the getopt() function in C:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Command line arguments example in C
- C program to print odd line contents of a File followed by even line content
- How to create a command-line progress bar in C/C++
- How to Count Variable Numbers of Arguments in C?
- Does C support function overloading?
- How can I return multiple values from a function?
- What is the purpose of a function prototype?
- What is evaluation order of function parameters in C?
- Importance of function prototype in C
- What happens when a function is called before its declaration in C?
- Comparator function of qsort() in C
- Power Function in C/C++
- strtoul() function in C/C++
- strtof function in C
- ispunct() function in C
- tmpnam() function in C
- _Noreturn function specifier in C
- strrchr() function in C/C++
- wcscspn() function in C/C++
- strspn() function in C
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.