summaryrefslogtreecommitdiff
path: root/bin/pwd/pwd.c
blob: fef433cfc89027695e0670fcb35e7cf94a2fe11a (plain)
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
#include "stddef.h"
#include <err.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
	const char *out = NULL;
	struct iovec iov[2];
	char opt, mode = 'L';
	char cwd[PATH_MAX];

	while ((opt = getopt(argc, argv, "")) != -1) {
		switch (opt) {
		case 'L':
		case 'P':
			mode = opt;
			break;
		default:
			write(STDERR_FILENO, "usage: pwd [-L|-P]\n", 20);
			return 1;
		}
	}

	if (getcwd(cwd, sizeof(cwd)) == NULL) {
		perror("pwd: getcwd");
		return 1;
	}

	if (mode == 'L') {
		const char *pwd;
		struct stat cst, pst;

		if ((pwd = getenv("PWD")) == NULL || *pwd != '/' ||
		    stat(pwd, &pst) < 0) {
			out = cwd;
		}

		if (stat(cwd, &cst) < 0) {
			perror("pwd: stat");
		}

		out = (pst.st_dev == cst.st_dev && pst.st_ino == cst.st_ino) ?
			      pwd :
			      cwd;
	}

	iov[0].iov_base = (char *)out;
	iov[0].iov_len = strlen(out);

	iov[1].iov_base = "\n";
	iov[1].iov_len = 1;

	if (writev(STDOUT_FILENO, iov, 2) < 0) {
		err(1, "pwd");
	}

	return 0;
}