C:Working with command line arguments

Almost all of the commands in Linux/Unix have options. An option for a commmand is a mechanism by which you provide additional parameters to the command to change its behavior. Take for example, the command ls is used to list the files in a directory. But to obtain a detailed listing of the files, the option -l is used. Similarly the -a option with ls allows to see all the hidden files (file names starting with .a). Commands with option removes the need for creating multiple commands to achieve a purpose.

To access the command line parameters, make sure that the main function() looks something like this

int main(int argc, char *argv[]) {
}

Now you can write a program which access every parameter that you pass using argv[0], argv[1],…. And the number of command line arguments passed by the user can be obtained from argc

Working with command line arguments in this manner is tedious. Linux/Unix provides the following functions to easily work with the command line arguments

  1. getopt()
  2. getopt_long()
  3. getopt_long_only()

Before delving deep into this topic, let’s take a look what is meant by long arguments. Most of the options in a command have both a long and a short form. For example, to list all the hidden files, one can write ls -a or ls –all. Here -a is a short argument and –a is a long argument. As mentioned earlier, some options may not have a long option. -l option of ls doesn’t have a long option. With this in mind, let’s continue to look at the various functions

  1. getopt()
  2. getopt_long()
  3. getopt_long_only()
About these ads