1/* See LICENSE file for copyright and license details. */
2
3
4#include <sys/stat.h>
5
6#include <stdio.h>
7#include <stdlib.h>
8#include <unistd.h>
9
10#include "util.h"
11
12static const char *
13getpwd(const char *cwd)
14{
15 const char *pwd;
16 struct stat cst, pst;
17
18 if (!(pwd = getenv("PWD")) || pwd[0] != '/' || stat(pwd, &pst) < 0)
19 return cwd;
20 if (stat(cwd, &cst) < 0)
21 eprintf("stat %s:", cwd);
22
23 return (pst.st_dev == cst.st_dev && pst.st_ino == cst.st_ino) ? pwd : cwd;
24}
25
26static void
27usage(void)
28{
29 eprintf("usage: %s [-LP]\n", argv0);
30}
31
32// ?man pwd: print working directory
33// ?man display the pathname of the current working directory
34int
35main(int argc, char *argv[])
36{
37 char cwd[PATH_MAX];
38 char mode = 'L';
39
40 ARGBEGIN {
41 // ?man -L: specify option flag
42 case 'L':
43 // ?man -P: specify option flag
44 case 'P':
45 mode = ARGC();
46 break;
47 default:
48 usage();
49 } ARGEND
50
51 if (!getcwd(cwd, sizeof(cwd)))
52 eprintf("getcwd:");
53 puts((mode == 'L') ? getpwd(cwd) : cwd);
54
55 return fshut(stdout, "<stdout>");
56}