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.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice BCA MCQs
- Apply for C Internship
- Watch Advanced C Programming Videos
- Buy C Books
- Apply for Computer Science Internship