Skip to main content

C Command Line Arguments

Command line arguments in C provide a powerful way to pass information to your program when it starts executing. This mechanism allows users to customize the program's behavior without modifying its source code.

What Are Command Line Arguments?

Command line arguments are values passed to a program when it is launched from the command line interface. They appear after the program name and are separated by spaces.

bash
./program arg1 arg2 arg3

How C Handles Command Line Arguments

In C, these arguments are accessible through parameters in the main() function:

c
int main(int argc, char *argv[])
{
// Program code
return 0;
}
  • argc (argument count): An integer containing the number of arguments passed to the program, including the program name itself.
  • argv (argument vector): An array of strings (char pointers) where each element represents one argument.

Understanding argc and argv

The relationship between these parameters is:

  • argc is at least 1, as the program name is always the first argument
  • argv[0] contains the program name or path
  • argv[1] through argv[argc-1] contain the actual command line arguments
  • argv[argc] is always NULL

Basic Example

Let's see a simple program that displays all command line arguments:

c
#include <stdio.h>

int main(int argc, char *argv[])
{
printf("Program name: %s\n", argv[0]);
printf("Number of arguments: %d\n", argc);

for (int i = 1; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}

return 0;
}

If you compile this program to create args and run it with:

bash
./args hello world 123

The output will be:

Program name: ./args
Number of arguments: 4
Argument 1: hello
Argument 2: world
Argument 3: 123

Parsing Numeric Arguments

Command line arguments are always passed as strings. To use them as numbers, you need to convert them:

c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
if (argc < 3) {
printf("Usage: %s <num1> <num2>\n", argv[0]);
return 1;
}

// Convert string arguments to integers
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);

printf("Sum: %d\n", num1 + num2);

return 0;
}

Processing Options and Flags

Programs often need to handle options like -h for help or -v for verbose mode:

c
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
int verbose = 0;

// Process command line options
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
verbose = 1;
} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
printf("Usage: %s [-v|--verbose] [-h|--help]\n", argv[0]);
printf(" -v, --verbose Enable verbose output\n");
printf(" -h, --help Display this help message\n");
return 0;
}
}

// Program logic
if (verbose) {
printf("Running in verbose mode...\n");
}

printf("Program executed successfully\n");

return 0;
}

Using getopt for Complex Argument Parsing

For more complex command line parsing, the getopt library is recommended:

c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
int opt;
int flag_a = 0;
int flag_b = 0;
char *value = NULL;

// Process options
while ((opt = getopt(argc, argv, "abv:")) != -1) {
switch (opt) {
case 'a':
flag_a = 1;
break;
case 'b':
flag_b = 1;
break;
case 'v':
value = optarg;
break;
default:
fprintf(stderr, "Usage: %s [-a] [-b] [-v value]\n", argv[0]);
return 1;
}
}

// Show results
printf("Flag a: %s\n", flag_a ? "enabled" : "disabled");
printf("Flag b: %s\n", flag_b ? "enabled" : "disabled");
if (value) {
printf("Value: %s\n", value);
}

// Process non-option arguments
for (int i = optind; i < argc; i++) {
printf("Non-option argument: %s\n", argv[i]);
}

return 0;
}

Best Practices

  1. Always validate user input: Check that the required number of arguments is provided
  2. Provide usage information: Show helpful error messages if arguments are missing or incorrect
  3. Handle different argument formats: Be flexible with how users can provide arguments
  4. Use appropriate conversion functions: Use atoi(), atof(), or strtol() family of functions for converting strings to numbers
  5. Consider using getopt: For complex command line interfaces, use the getopt or getopt_long functions

Common Applications

Command line arguments are particularly useful for:

  • Configuration settings
  • Input and output file paths
  • Processing modes or options
  • Batch processing of multiple inputs
  • Scripting and automation

Conclusion

Command line arguments provide a flexible way to configure C programs at runtime. By mastering them, you can create more versatile applications that can be easily integrated into scripts and automation workflows.

Understanding command line arguments is a crucial skill for any C programmer, especially when developing utilities and tools that need to be used in different scenarios without recompilation.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)