This C Tutorial explains Command Line Arguments in C Programming with examples.
Linux system gives us a command environment where we execute commands to perform certain tasks. For example,
ls command lists files and directories in a directory
ll gives long listing of files and directories in a directory
Actually, such commands are programs. And we may or may not pass arguments to programs for specific needs.
How can we pass arguments to ours’ C programs?
Well! We can pass arguments to a C program through command environment. These arguments go into program’s main() parameters. A C program’s main takes generally two arguments, these are, first an integer type and the other an array of pointers-to-char.
int main(int argc, char *argv[]) { /* statements */ }
argc stands for argument’s count while argv contains argument values. These names haven’t any magic associated with them and you can use any of yours’ choice for them. argv[] array is terminated by a NULL string. Therefore, you can use either of two arguments to count on no. of arguments passed to a C program.
Consider the below given command, say, to compile a program named “cmd.c”,
gcc -o cmd cmd.c ./cmd -abc -def hello, command line" "you pass arguments to program" "great"
Firstly, we compiled cmd.c to a binary file with name cmd then we run the binary file cmd together with several arguments. All the arguments including program name, any options beginning with dash ‘-‘ followed by strings are passed into main’s parameters of cmd.c. Arguments passed from the command into a program are called command-line arguments. Let’s see a simple C program processing command-line arguments,
int main(int argc, char *argv[]) { while (*argv != NULL) { printf("%s", *argv); argv++; } return 0; }
Notice that above program doesn’t do useful except it prints on the terminal arguments passed to it with the program name.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Apply for C Internship
- Apply for Computer Science Internship
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Check C Books