Command line arguments in C
Command-Line Arguments in C
Command-line arguments are a way to pass information or inputs to a C program when you run it from the command line or terminal.
They provide flexibility and let users control the program’s behavior without changing the code.
Syntax in C
Parameters
-
argc (Argument Count)
-
Integer representing the number of command-line arguments
-
Includes the program name
-
-
argv (Argument Vector)
-
Array of strings containing the arguments
-
argv[0]→ program name -
argv[1], argv[2], ...→ user arguments
-
Example 1: Printing Command-Line Arguments
Running the Program
Expected Output
Important Points
-
Data Type: Arguments are passed as strings
-
Conversion: Use functions like
atoi(),atof()to convert values -
Error Handling: Always check argument count
-
Applications:
-
Passing filenames
-
Configuration settings
-
User inputs
-
Example 2: Add Two Numbers Using Command-Line Arguments
Run
Note: atoi() converts string to integer.
Example 3: Display Contents of Files Passed as Arguments
Example 4: Simulation of Copy Command
(Copy contents from one file to another)
Comments
Post a Comment