Command-Line Arguments
Understanding Command-Line Arguments
Argument Components
graph TD
A[Command-Line Arguments] --> B[Argument Count: argc]
A --> C[Argument Vector: argv]
B --> D[Total number of arguments]
C --> E[Array of string pointers]
Basic Argument Structure
int main(int argc, char* argv[]) {
// argc: Argument Count
// argv: Argument Vector
}
Argument Processing Techniques
Argument Parsing Example
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
// Display total argument count
std::cout << "Total arguments: " << argc << std::endl;
// Iterate through arguments
for (int i = 0; i < argc; ++i) {
std::cout << "Argument " << i << ": " << argv[i] << std::endl;
}
return 0;
}
Argument Types and Handling
Argument Type |
Description |
Example |
Program Name |
First argument (argv[0]) |
./program |
Positional Arguments |
Sequential parameters |
input.txt output.txt |
Optional Arguments |
Prefixed with - or -- |
-v, --verbose |
Advanced Argument Processing
Argument Validation
int main(int argc, char* argv[]) {
// Check minimum required arguments
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " <input>" << std::endl;
return 1;
}
// Convert argument to string
std::string input = argv[1];
// Validate input
if (input.empty()) {
std::cerr << "Invalid input" << std::endl;
return 1;
}
return 0;
}
Practical Scenarios on LabEx
File Processing Example
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0]
<< " <input_file> <output_file>" << std::endl;
return 1;
}
std::ifstream input_file(argv[1]);
std::ofstream output_file(argv[2]);
if (!input_file) {
std::cerr << "Cannot open input file" << std::endl;
return 1;
}
if (!output_file) {
std::cerr << "Cannot open output file" << std::endl;
return 1;
}
// File processing logic
std::string line;
while (std::getline(input_file, line)) {
output_file << line << std::endl;
}
return 0;
}
Compilation and Execution
## Compile the program
g++ -std=c++17 argument_processor.cpp -o processor
## Run with arguments
./processor input.txt output.txt
Best Practices
- Always validate argument count
- Check argument validity
- Provide clear usage instructions
- Handle potential errors gracefully
- Use modern C++ techniques for argument processing
Common Argument Parsing Challenges
graph TD
A[Argument Parsing Challenges]
A --> B[Insufficient Arguments]
A --> C[Invalid Argument Types]
A --> D[Complex Argument Formats]
A --> E[Error Handling]