In this step, you will create a practical command-line tool that demonstrates the skills you've learned about parsing and handling command-line arguments.
You'll implement a simple command-line calculator that performs basic arithmetic operations based on user-provided arguments.
- Create a new file named
calc.c
in the ~/project
directory:
cd ~/project
touch calc.c
- Add the following code to create a command-line calculator:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function prototypes
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
int main(int argc, char* argv[]) {
// Check for correct number of arguments
if (argc != 4) {
fprintf(stderr, "Usage: %s <operation> <num1> <num2>\n", argv[0]);
fprintf(stderr, "Operations: add, sub, mul, div\n");
return 1;
}
// Parse operation
char* operation = argv[1];
// Convert arguments to numbers
double num1 = atof(argv[2]);
double num2 = atof(argv[3]);
// Perform calculation based on operation
double result = 0;
if (strcmp(operation, "add") == 0) {
result = add(num1, num2);
printf("%.2f + %.2f = %.2f\n", num1, num2, result);
} else if (strcmp(operation, "sub") == 0) {
result = subtract(num1, num2);
printf("%.2f - %.2f = %.2f\n", num1, num2, result);
} else if (strcmp(operation, "mul") == 0) {
result = multiply(num1, num2);
printf("%.2f * %.2f = %.2f\n", num1, num2, result);
} else if (strcmp(operation, "div") == 0) {
// Check for division by zero
if (num2 == 0) {
fprintf(stderr, "Error: Division by zero\n");
return 1;
}
result = divide(num1, num2);
printf("%.2f / %.2f = %.2f\n", num1, num2, result);
} else {
fprintf(stderr, "Error: Invalid operation\n");
fprintf(stderr, "Supported operations: add, sub, mul, div\n");
return 1;
}
return 0;
}
// Arithmetic operation functions
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
return a / b;
}
- Compile the program:
gcc calc.c -o calc
- Run the calculator with different operations:
## Addition
./calc add 5 3
## Subtraction
./calc sub 10 4
## Multiplication
./calc mul 6 7
## Division
./calc div 15 3
## Error cases
./calc div 10 0
./calc pow 5 2
Example output:
## Addition
5.00 + 3.00 = 8.00
## Subtraction
10.00 - 4.00 = 6.00
## Multiplication
6.00 * 7.00 = 42.00
## Division
15.00 / 3.00 = 5.00
## Division by zero
Error: Division by zero
## Invalid operation
Error: Invalid operation
Supported operations: add, sub, mul, div
Key Concepts
- Combine argument parsing with functional logic
- Handle different operation scenarios
- Provide clear error messages
- Use separate functions for different operations
- Validate input and handle edge cases