|
2 | 2 | * Exercise 7-1. Write a program that converts upper case to lower or lower |
3 | 3 | * case to upper, depending on the name it is invoked with, as found in |
4 | 4 | * argv[0]. |
| 5 | + * |
5 | 6 | * By Faisal Saadatmand |
6 | 7 | */ |
7 | 8 |
|
8 | | -#include <stdio.h> |
9 | 9 | #include <ctype.h> |
| 10 | +#include <stdio.h> |
10 | 11 | #include <string.h> |
11 | 12 |
|
12 | | -int main(int argc, char *argv[]) |
| 13 | +/* parsename: if program name starts with '.', parse it, i.e. trim the full |
| 14 | + * pathname and return name only, otherwise return name as is. */ |
| 15 | +char *parsename(char *name) |
13 | 16 | { |
14 | | - int c, function; |
15 | | - char *pname; /* program name */ |
16 | | - |
17 | | - if (argc != 1) |
18 | | - return -1; |
| 17 | + return name[0] == '.' ? strrchr(name, '/') + 1 : name; |
| 18 | +} |
19 | 19 |
|
20 | | - pname = (strrchr(*argv, '/')) + 1; /* parse program name */ |
| 20 | +int main(int argc, char *argv[]) |
| 21 | +{ |
| 22 | + int c; |
| 23 | + int (*func)(int); /* function pointer to tolower or toupper */ |
| 24 | + char *prog; /* program name */ |
21 | 25 |
|
22 | | - if (strcmp("tolower", pname) == 0) |
23 | | - function = 0; |
24 | | - else if (strcmp("toupper", pname) == 0) |
25 | | - function = 1; |
| 26 | + --argc; |
| 27 | + prog = parsename(argv[0]); |
| 28 | + if (!strcmp("tolower", prog)) |
| 29 | + func = tolower; |
| 30 | + else if (!strcmp("toupper", prog)) |
| 31 | + func = toupper; |
26 | 32 | else { |
27 | | - printf("%s: Unknown function: ", pname); |
28 | | - printf("Rename program to tolower or toupper.\n"); |
| 33 | + printf("Error: rename program to tolower or toupper\n"); |
29 | 34 | return -1; |
30 | 35 | } |
31 | 36 | while ((c = getchar()) != EOF) |
32 | | - putchar((function) ? toupper(c) : tolower(c)); |
| 37 | + putchar(func(c)); |
33 | 38 | return 0; |
34 | 39 | } |
0 commit comments