getopt in C programming
getopt()
function in C programming could use to parse command line options.
Switch statement used to return value from getopt
If takes an argument from the usage, ':'
presents.(From the while loop)
Here’s an example what I learned from the class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
@author Sehyun Cho
Salary calculator that do bonuses and raises to a base salary
as well as a veterans bump. Taxes will be deducted from the
salary as well. Using getopt to parse the command line, to get salary.
-b: 5000 bonus on top of the salary, adds to the base.
-r: multiplies the base by percentage and adding up.
-v: 6000 bonus on top of the salary, adds to the base.
-t: multiplies the base by percentage and subtracting.
getopt command line below:
usage: salary [-bv] [-r rnum] -t tnum base
*/
// Headers
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// Main fuction
int main(int argc, char **argv)
{
// Declare variables
extern char *optarg;
extern int optind;
int c, err = 0;
int tnum, rnum = 0;
int tflag = 0;
int base;
double rAmount, vBonus, bBonus, tax, salary;
// Declare usage
static char usage[] = "usage %s [-bv] [-r rnum] -t tnum value\n";
// Switch statement - Since 'r' and 't' take argument, ':' contain.
while ((c = getopt (argc, argv, "vr:bt:")) != -1)
{
switch(c)
{
case 'v':
// Assign bonus 6000 if case v
vBonus = 6000;
break;
case 'r':
rnum = atoi(optarg);
// Restrict r value in between 2 and 10
if(rnum < 2 || rnum > 10)
{
fprintf(stderr, "%s:Error. The rnum should be between 2 and 10.\n");
exit(1);
}
rAmount = rnum * 0.01;
break;
case 'b':
// Assign bonus 5000 if case b
bBonus = 5000;
break;
case 't':
tnum = atoi(optarg);
// Restrict t value in between 5 and 30
if(tnum < 5 || tnum > 30)
{
fprintf(stderr, "%s:Error. The tnum should be between 5 and 30.\n");
exit(1);
}
tflag = 1;
tax = tnum * 0.01;
break;
case '?':
// case '?' shows marks as an error
err = 1;
break;
}
}
}