Practical Coding Patterns
Common Main Function Implementation Strategies
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <input>\n", argv[0]);
return EXIT_FAILURE;
}
printf("First argument: %s\n", argv[1]);
return EXIT_SUCCESS;
}
Error Handling Patterns
Argument Validation Techniques
int main(int argc, char *argv[]) {
// Minimum argument check
if (argc != 3) {
fprintf(stderr, "Error: Exactly 2 arguments required\n");
return EXIT_FAILURE;
}
// Type conversion with error checking
int value;
char *endptr;
value = (int)strtol(argv[1], &endptr, 10);
if (*endptr != '\0') {
fprintf(stderr, "Invalid numeric input\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Argument Processing Workflow
graph TD
A[Program Start] --> B{Argument Count Check}
B --> |Insufficient| C[Display Usage]
B --> |Sufficient| D[Validate Arguments]
D --> |Valid| E[Execute Main Logic]
D --> |Invalid| F[Error Handling]
E --> G[Return Result]
Advanced Argument Handling Patterns
Flexible Argument Processing
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
char *filename = NULL;
int verbose = 0;
while ((opt = getopt(argc, argv, "f:v")) != -1) {
switch (opt) {
case 'f':
filename = optarg;
break;
case 'v':
verbose = 1;
break;
default:
fprintf(stderr, "Usage: %s [-f filename] [-v]\n", argv[0]);
return EXIT_FAILURE;
}
}
if (filename) {
printf("Processing file: %s\n", filename);
}
if (verbose) {
printf("Verbose mode enabled\n");
}
return EXIT_SUCCESS;
}
Argument Handling Strategies
Strategy |
Description |
Use Case |
LabEx Recommendation |
Basic Validation |
Simple argument count check |
Small scripts |
Beginners |
Type Conversion |
Numeric input validation |
Numeric processing |
Intermediate |
Getopt Processing |
Complex option handling |
CLI tools |
Advanced |
Best Practices
- Always validate input arguments
- Provide clear usage instructions
- Use standard error for error messages
- Return appropriate exit codes
- Handle potential edge cases
Error Code Conventions
graph LR
A[EXIT_SUCCESS: 0] --> B[Successful Execution]
C[EXIT_FAILURE: 1] --> D[General Error]
E[Custom Codes: 2-125] --> F[Specific Error Conditions]
Compilation and Execution
Compile with gcc on Ubuntu:
gcc -o argument_processor main.c
./argument_processor -f input.txt -v