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
argv
array: the name of the program
Let’s take the example of the C compiler we use to run our programs, like this:
gcc hello.c -o hello
If this was our program, we’d have argc
being 4 and argv
being an array containing
gcc
hello.c
-o
hello
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.
Download my free C Handbook
More clang tutorials:
- Introduction to the C Programming Language
- C Variables and types
- C Constants
- C Operators
- C Conditionals
- How to work with loops in C
- Introduction to C Arrays
- How to determine the length of an array in C
- Introduction to C Strings
- How to find the length of a string in C
- Introduction to C Pointers
- Looping through an array with C
- Booleans in C
- Introduction to C Functions
- How to use NULL in C
- Basic I/O concepts in C
- Double quotes vs single quotes in C
- How to return a string from a C function
- How to solve the implicitly declaring library function warning in C
- How to check a character value in C
- How to print the percentage character using `printf()` in C
- C conversion specifiers and modifiers
- How to access the command line parameters in C
- Scope of variables in C
- Can you nest functions in C?
- Static variables in C
- C Global Variables
- The typedef keyword in C
- C Enumerated Types
- C Structures
- C Header Files
- The C Preprocessor