Start Coding

Topics

Command-Line Arguments in C

Command-line arguments are a powerful feature in C programming that allow users to pass information to a program when it starts. They provide a flexible way to customize program behavior without modifying the source code.

Understanding Command-Line Arguments

In C, command-line arguments are passed to the main() function. The function signature typically looks like this:

int main(int argc, char *argv[])

Here, argc (argument count) represents the number of arguments, and argv (argument vector) is an array of strings containing the arguments.

Accessing Command-Line Arguments

You can access command-line arguments using array notation. The first element, argv[0], always contains the program name itself.


#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Program name: %s\n", argv[0]);
    
    for (int i = 1; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }
    
    return 0;
}

Common Use Cases

  • Passing configuration options
  • Specifying input/output file names
  • Setting program modes or flags

Converting Arguments to Other Types

Command-line arguments are passed as strings. To use them as other data types, you'll need to convert them. The C Standard Library provides functions for this purpose:


#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;
    }
    
    int num1 = atoi(argv[1]);
    int num2 = atoi(argv[2]);
    
    printf("Sum: %d\n", num1 + num2);
    
    return 0;
}

Best Practices

  • Always check the number of arguments provided
  • Validate and sanitize input to prevent security vulnerabilities
  • Provide clear usage instructions when incorrect arguments are given
  • Consider using a library for complex argument parsing

Error Handling

Proper error handling is crucial when working with command-line arguments. Always check for potential errors and provide meaningful feedback to the user.

Conclusion

Command-line arguments enhance the flexibility and usability of C programs. By mastering this concept, you can create more versatile and user-friendly applications. Remember to handle arguments carefully and provide clear documentation for your program's usage.