morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base.git
Log | Files | Refs

pwd.c (825B)


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