How Command Line Arguments are Passed and Processed in C?

«
»
This C Tutorial explains how Command Line Arguments are Passed and Processed in C.

Let’s try to understand through a simple C program,

/* cmd_args.c -- how to pass and access command line arguments */
#include <stdio.h>
 
void process_cmd_args(char **);
 
int main(int argc, char *argv[])
{
    puts("**Program processes Command Line Arguments**");
    /* process cmd-line arguments */
    /* process options and file names given as arguments on command */
    process_cmd_args(argv);
 
    return 0;
}
 
void process_cmd_args(char **string)
{
    char opt;
    /* skip the 1st string which is program name */
    /* process any options begin with - */
    while (*++string != NULL && **string == '-') {
            /* process option */
            while ((opt = *++*string) != '\0') {
                            switch (opt) {
                                    case 'a': puts("a");
                                            break;
                                    case 'b': puts("b");
                                            break;
                                    case 'c': puts("c");
                                            break;
                                    default: puts("option not known");
                                            break;
                             }
            }
    }
    /* Process file names if there's any otherwise read from terminal  */
    if (*string  == NULL)
            puts("process_standard_input()");
    else {
            do {
                    puts("Processing File Argument.");
 
            } while (*++string != NULL);
    }
 
}

Output when above program executed with

advertisement

# gcc -o cmd_args cmd_args.c
# ./cmd_args -ab -c -d “hello, world of Linux” “C programs”

**Program processes Command Line Arguments**
a
b
c
option not known
Processing File Argument.
Processing File Argument.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn