1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/** * File: args.c * Author: Risto Heinsar * Created: 10.11.2014 * Modified: 12.08.2024 * * Description: Program demonstrates accessing command line arguments * when passed during the execution of the program. * * Usage: ./program_name arg1 arg2 arg3 ... */ #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { printf("Got %d command line arguments\n", argc); // Loops over all arguments as strings for (int i = 0; i < argc; i++) { printf("argv[%d] = %s\n", i, argv[i]); } printf("\n"); // Loop over the arguments once more for (int i = 0; i < argc; i++) { // Grab the length of the current argument int n = strlen(argv[i]); // Print the current argument, character by character for (int j = 0; j < n; j++) { printf("%c ", argv[i][j]); } printf("\n"); } return 0; } |
Some notable points
- This form of main function ( int main(int argc, char *argv[]) ) should only be used when you intend to accept command line arguments.
- It doesn’t matter which form of argument vector you are using. Both *argv[] and **argv are equivalent.
- argc will tell you how many arguments were passed to your program. This is also the length of the argument vector.
- argc value will be 1, if no arguments were passed to the program.
- argv is the argument vector that contains all passed arguments as strings. It reality it’s an array of pointers to strings. Each pointer will be pointing at one of the arguments (strings).
- argv[0] contains the name of the executable (and how it was executed)
- argv[i] contains the i-th argument as a string. I.e. argv[1] contains the first argument.
- All argumetns are passed as strings, even if they only contain numbers.