Command Line Arguments in C
Learn how to use command line arguments in C using argc and argv. Understand how to read input from the terminal when starting a program on Debian 12 using Vim.
Command Line Arguments in C
Command line arguments allow you to pass values to a C program when you run it from the terminal. This is very useful for tools, scripts, and automation tasks. These arguments are accessed using argc and argv.
What Are argc and argv?
- argc: Argument Count. It shows how many arguments were passed to the program, including the program name itself.
- argv: Argument Vector. It is an array of strings that holds each argument passed to the program.
Basic Example
This program prints all the command line arguments provided by the user.
#include
int main(int argc, char *argv[])
printf(\\"Total arguments: %d\\\
\\", argc);
for (int i = 0; i < argc; i++)
printf(\\"Argument %d: %s\\\
\\", i, argv[i]);
return 0;
Explanation
- The
argcvalue tells how many arguments were passed. argv[0]always contains the program name.- The loop prints all arguments, including the name of the program.
Compiling and Running with Arguments
To run the compiled program with arguments:
gcc args.c -o args
./args Hello World 123
Expected Output
Total arguments: 4
Argument 0: ./args
Argument 1: Hello
Argument 2: World
Argument 3: 123
Use Cases
Command line arguments are useful when you want to:
- Configure program behavior at runtime
- Pass file names or paths as parameters
- Provide dynamic input without user interaction
Conclusion
Using argc and argv enables dynamic, scriptable, and more flexible C programs. Try passing different arguments to explore how they behave.
Subscribe to Our YouTube for More
https://blog.arashtad.com/updates/command-line-arguments-in-c/?feed_id=13536&_unique_id=689d95b998fc7
Comments
Post a Comment