Command-line Arguments in C

By: Daniel Malcolm Emailed: 1598 times Printed: 2044 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

In environments that support C, there is a way to pass command-line arguments or parameters to a program when it begins executing. When main is called, it is called with two arguments. The first (conventionally called argc, for argument count) is the number of command-line arguments the program was invoked with; the second (argv, for argument vector) is a pointer to an array of character strings that contain the arguments, one per string. We customarily use multiple levels of pointers to manipulate these character strings.

The simplest illustration is the program echo, which echoes its command-line arguments on a single line, separated by blanks. That is, the command

   echo hello, world
prints the output
   hello, world
By convention, argv[0] is the name by which the program was invoked, so argc is at least 1. If argc is 1, there are no command-line arguments after the program name. In the example above, argc is 3, and argv[0], argv[1], and argv[2] are "echo", "hello,", and "world" respectively. The first optional argument is argv[1] and the last is argv[argc-1]; additionally, the standard requires that argv[argc] be a null pointer.

The first version of echo treats argv as an array of character pointers:

   #include <stdio.h>

   /* echo command-line arguments; 1st version */
   main(int argc, char *argv[])
   {
       int i;

       for (i = 1; i < argc; i++)
           printf("%s%s", argv[i], (i < argc-1) ? " " : "");
       printf("\n");
       return 0;
   }
Since argv is a pointer to an array of pointers, we can manipulate the pointer rather than index the array. This next variant is based on incrementing argv, which is a pointer to pointer to char, while argc is counted down:
   #include <stdio.h>

   /* echo command-line arguments; 2nd version */
   main(int argc, char *argv[])
   {
       while (--argc > 0)
           printf("%s%s", *++argv, (argc > 1) ? " " : "");
       printf("\n");
       return 0;
   }
Since argv is a pointer to the beginning of the array of argument strings, incrementing it by 1 (++argv) makes it point at the original argv[1] instead of argv[0]. Each successive increment moves it along to the next argument; *argv is then the pointer to that argument. At the same time, argc is decremented; when it becomes zero, there are no arguments left to print.

Alternatively, we could write the printf statement as

   printf((argc > 1) ? "%s " : "%s", *++argv);
This shows that the format argument of printf can be an expression too.

As a second example, let us make some enhancements to the pattern-finding program Following the lead of the UNIX program grep, let us enhance the program so the pattern to be matched is specified by the first argument on the command line.

   #include <stdio.h>
   #include <string.h>
   #define MAXLINE 1000

   int getline(char *line, int max);

   /* find:  print lines that match pattern from 1st arg */
   main(int argc, char *argv[])
   {
       char line[MAXLINE];
       int found = 0;

       if (argc != 2)
           printf("Usage: find pattern\n");
       else
           while (getline(line, MAXLINE) > 0)
               if (strstr(line, argv[1]) != NULL) {
                   printf("%s", line);
                   found++;
               }
       return found;
   }
The standard library function strstr(s,t) returns a pointer to the first occurrence of the string t in the string s, or NULL if there is none. It is declared in <string.h>.

The model can now be elaborated to illustrate further pointer constructions. Suppose we want to allow two optional arguments. One says ``print all the lines except those that match the pattern;'' the second says ``precede each printed line by its line number.''

A common convention for C programs on UNIX systems is that an argument that begins with a minus sign introduces an optional flag or parameter. If we choose -x (for ``except'') to signal the inversion, and -n (``number'') to request line numbering, then the command

   find -x -npattern
will print each line that doesn't match the pattern, preceded by its line number.

Optional arguments should be permitted in any order, and the rest of the program should be independent of the number of arguments that we present. Furthermore, it is convenient for users if option arguments can be combined, as in

   find -nx pattern
Here is the program:
   #include <stdio.h>
   #include <string.h>
   #define MAXLINE 1000

   int getline(char *line, int max);

   /* find: print lines that match pattern from 1st arg */
   main(int argc, char *argv[])
   {
       char line[MAXLINE];
       long lineno = 0;
       int c, except = 0, number = 0, found = 0;

       while (--argc > 0 && (*++argv)[0] == '-')
           while (c = *++argv[0])
               switch (c) {
               case 'x':
                   except = 1;
                   break;
               case 'n':
                   number = 1;
                   break;
               default:
                   printf("find: illegal option %c\n", c);
                   argc = 0;
                   found = -1;
                   break;
               }
       if (argc != 1)
           printf("Usage: find -x -n pattern\n");
       else
           while (getline(line, MAXLINE) > 0) {
               lineno++;
               if ((strstr(line, *argv) != NULL) != except) {
                   if (number)
                       printf("%ld:", lineno);
                   printf("%s", line);
                   found++;
               }
           }
       return found;
   }
argc is decremented and argv is incremented before each optional argument. At the end of the loop, if there are no errors, argc tells how many arguments remain unprocessed and argv points to the first of these. Thus argc should be 1 and *argv should point at the pattern. Notice that *++argv is a pointer to an argument string, so (*++argv)[0] is its first character. (An alternate valid form would be **++argv.) Because [] binds tighter than * and ++, the parentheses are necessary; without them the expression would be taken as *++(argv[0]). In fact, that is what we have used in the inner loop, where the task is to walk along a specific argument string. In the inner loop, the expression *++argv[0] increments the pointer argv[0]!

It is rare that one uses pointer expressions more complicated than these; in such cases, breaking them into two or three steps will be more intuitive.


C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

As C does not support Function Overloading, there can be only one definition of main function. So, how can we access default arguments when main function with no parameters is called.

View Tutorial          By: N at 2013-03-06 00:27:14

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Daniel Malcolm
javac options in Java
Operator Precedence in Java
Calling Multiple Listeners in JSF
Using free() Function in C
ForwardAction in Struts
Listing Files and Directories sample program in C
Binary Tree - (Self-referential Structures) example program in C
A simple program using EL in JSP
Command-line Arguments in C
Example Calculator program in C - describing use of External Variables in C
Assignment Operators and Expressions in C
The for statement in C
JSF Basics
assert() Versus Exceptions in C++
RMS Basics in J2ME

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Using memset(), memcpy(), and memmove() in C
UNIX read and write system calls sample program in C
Constants and escape sequences in C
Table Lookup - hashtab - example program in C
fgets(), fputs() - Line Input and Output - sample program in C
A Storage Allocator sample program in C
Using realloc() Function in C
ERRNO.H Header File in C
Writing The First C program
Formatting with printf in C
Calculator in C
Passing double value to a function in C
Printing a simple histogram in C
Find square and square root for a given number in C
Getting Started with C
Most Emailed Articles (in C)
Conditional Expressions in C
fgets(), fputs() - Line Input and Output - sample program in C
Symbolic Constants using #define in C
#if, #elif, #ifndef, #ifdef in C (Conditional Inclusion)
Address Arithmetic and pointers in C
Character Pointers and Functions in C
Initialization of Pointer Arrays in C
Pointers to Structures example program in C
Using printf function in C
A Storage Allocator sample program in C
Using free() Function in C
The C Character Set
Writing The First C program
Formatting with printf in C
while, do while and for loops in C