So I'm in Linux and I want to have a program accept arguments when you execute it from the command line.
For example,
./myprogram 42 -b -s
So then the program would store that number 42 as an int and execute certain parts of code depending on what arguments it gets like -b or -s.
These command line arguments are handled by the main() function. If you want to pass command line arguments then you will have to define the main() function with two arguments. The first argument defines the number of command line arguments and the second argument is the list of command line arguments.
To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.
Every executable accepts different arguments and interprets them in different ways. For example, entering C:\abc.exe /W /F on a command line would run a program called abc.exe and pass two command line arguments to it: /W and /F. The abc.exe program would see those arguments and handle them internally.
What are Command Line Arguments in C? Command line arguments are nothing but simply arguments that are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution.
You could use getopt.
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main (int argc, char **argv) { int bflag = 0; int sflag = 0; int index; int c; opterr = 0; while ((c = getopt (argc, argv, "bs")) != -1) switch (c) { case 'b': bflag = 1; break; case 's': sflag = 1; break; case '?': if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } printf ("bflag = %d, sflag = %d\n", bflag, sflag); for (index = optind; index < argc; index++) printf ("Non-option argument %s\n", argv[index]); return 0; }
In C, this is done using arguments passed to your main()
function:
int main(int argc, char *argv[]) { int i = 0; for (i = 0; i < argc; i++) { printf("argv[%d] = %s\n", i, argv[i]); } return 0; }
More information can be found online such as this Arguments to main article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With