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