Skip to content

Commit 7dfe28a

Browse files
committed
use function pointer and improve prog name parsing
1 parent d6ca6c5 commit 7dfe28a

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

chapter07/7-1.c

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,38 @@
22
* Exercise 7-1. Write a program that converts upper case to lower or lower
33
* case to upper, depending on the name it is invoked with, as found in
44
* argv[0].
5+
*
56
* By Faisal Saadatmand
67
*/
78

8-
#include <stdio.h>
99
#include <ctype.h>
10+
#include <stdio.h>
1011
#include <string.h>
1112

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)
1316
{
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+
}
1919

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 */
2125

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;
2632
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");
2934
return -1;
3035
}
3136
while ((c = getchar()) != EOF)
32-
putchar((function) ? toupper(c) : tolower(c));
37+
putchar(func(c));
3338
return 0;
3439
}

0 commit comments

Comments
 (0)