Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
In your C programs, you might have the need to accept parameters from the command line when the command launches.
For simple needs, all you need to do so is change the main() function signature from
int main(void)
to
int main (int argc, char *argv[])
argc is an integer number that contains the number of parameters that were provided in the command line.
argv is an array of strings.
When the program starts, we are provided the arguments in those 2 parameters.
Note that there’s always at least one item in the
argvarray: the name of the program
Let’s take the example of the C compiler we use to compile our programs, like this:
gcc hello.c -o hello
If our program were invoked with those four arguments, we’d have argc equal to 4 and argv an array containing
gcchello.c-ohello
Let’s write a program that prints the arguments it receives:
#include <stdio.h>
int main (int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
}
If the name of our program is hello and we run it like this: ./hello, we’d get this as output:
./hello
If we pass some random parameters, like this: ./hello a b c we’d get this output to the terminal:
./hello
a
b
c
This system works great for simple needs. For more complex needs, there are commonly used packages like getopt.
Lessons in this unit:
| 0: | Introduction |
| 1: | Input and output |
| 2: | Variable scope |
| 3: | Static variables |
| 4: | Global variables |
| 5: | Type definitions |
| 6: | Enumerations |
| 7: | Structures |
| 8: | ▶︎ Command line parameters |
| 9: | Header files |
| 10: | The preprocessor |
| 11: | NULL values |
| 12: | Boolean values |
| 13: | Nesting functions |
| 14: | Conversion specifiers |
| 15: | Using quotes |
| 16: | String length |
| 17: | Returning strings |
| 18: | Array length |
| 19: | Looping through arrays |
| 20: | Checking character values |
| 21: | Printing percentage signs |
| 22: | Troubleshooting: Implicit function declarations |