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

# 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
advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.