Major `cat` improvements
[lab.git] / pwd.c
blob308a57a354bcdb47b3a2ad61da0b34ccc306344c
1 /* `pwd.c` - return working directory name
2 Copyright (c) 2022, Alan Potteiger
3 See `LICENSE` for copyright and license details */
5 #define _POSIX_C_SOURCE 200809L
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <unistd.h>
11 static const char *usage = {
12 "usage: pwd [-L|-P]\n"
15 int
16 main(int argc, char *argv[])
18 char c;
19 char *wd, *p;
20 int flag;
22 /* 0 == -L
23 1 == -P */
24 flag = 0;
26 while ((c = getopt(argc, argv, "LP")) != -1) {
27 switch (c) {
28 case 'L':
29 flag = 0;
30 break;
31 case 'P':
32 flag = 1;
33 break;
34 case '?':
35 default:
36 fputs(usage, stderr);
37 return 1;
41 if (flag)
42 goto pflag;
44 /* -L */
45 wd = getenv("PWD");
46 if (wd == NULL)
47 goto pflag;
49 /* test pathname from $PWD for ./ or ../
50 if they exist, jump to the -P option */
51 p = wd;
52 for (; *p != '\0'; p++) {
53 if (*p == '/')
54 continue;
55 if (*p == '.') {
56 if (*(p+1) == '.' && *(p+1) == '/')
57 goto pflag;
58 if (*(p+1) == '/')
59 goto pflag;
63 printf("%s\n", wd);
64 return 0;
66 pflag: /* -P */
67 wd = getcwd(NULL, 0);
68 if (wd == NULL) {
69 perror("pwd");
70 return 1;
73 printf("%s\n", wd);
75 free(wd);
76 return 0;