Command-Line Arguments
1. Introduction
Command-line arguments are values passed to a C program at the time of execution through the command prompt or terminal. Instead of taking input from the keyboard during program execution, command-line arguments allow the user to provide input before the program starts running.
They are very useful in:
-
System programs
-
Utility software
-
File processing programs
-
Automation and scripting
2. Need for Command-Line Arguments
Command-line arguments are used when:
-
Input is required before program execution
-
Multiple inputs need to be passed quickly
-
Programs are executed repeatedly with different values
Example (Real-Life)
Here, source.txt and destination.txt are command-line arguments.
3. main() Function with Command-Line Arguments
In C, command-line arguments are received through the main() function.
Syntax
Explanation
-
argc→ Argument count -
argv→ Argument vector (array of strings)
4. Understanding argc
-
argcstores the total number of command-line arguments -
It always has a minimum value of 1
-
argv[0]stores the program name
Example
argc = 3
5. Understanding argv
-
argvis an array of character pointers -
Each element stores one argument as a string
| Argument | Stored In |
|---|---|
| Program name | argv[0] |
| First argument | argv[1] |
| Second argument | argv[2] |
6. Simple Program Using Command-Line Arguments
Example Program
7. Passing Numbers as Command-Line Arguments
Command-line arguments are passed as strings, so they must be converted to numbers.
Conversion Functions
-
atoi()– string to integer -
atof()– string to float
Example: Adding Two Numbers
8. Checking Number of Arguments
Always validate the number of arguments using argc.
Example
9. Command-Line Arguments with Files
Command-line arguments are often used for file handling.
Example
Program Example
10. Advantages of Command-Line Arguments
-
Faster input
-
No need for user interaction
-
Useful for automation
-
Suitable for large programs
11. Limitations of Command-Line Arguments
-
Limited input size
-
Not user-friendly for beginners
-
Requires correct syntax
12. Common Errors
-
Accessing
argvwithout checkingargc -
Forgetting arguments
-
Passing wrong data type
-
Not converting strings to numbers
13. Real-Life Applications
-
Compiler commands
-
File copy and delete utilities
-
Batch processing programs
-
System tools
14. Best Practices
-
Always check
argc -
Display proper usage message
-
Validate argument values
-
Use meaningful argument names
15. Summary Table
| Term | Meaning |
|---|---|
argc |
Argument count |
argv |
Argument vector |
argv[0] |
Program name |
atoi() |
String to integer |
16. Conclusion
Command-line arguments in C allow programs to receive input at execution time. By using argc and argv, programmers can create flexible and powerful programs that accept inputs quickly and efficiently. This concept is essential for developing system-level and real-world C applications.