From 5e90292fcb70670916844210d2f6248c78a1d870 Mon Sep 17 00:00:00 2001 From: Alan Potteiger Date: Tue, 22 Nov 2022 23:09:54 +0100 Subject: [PATCH] `pwd` implemented --- Makefile | 2 +- pwd.c | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 pwd.c diff --git a/Makefile b/Makefile index b96096d..3de3641 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -BIN=sleep cat +BIN=cat pwd sleep CFLAGS=-std=c99 all: $(BIN) clean: diff --git a/pwd.c b/pwd.c new file mode 100644 index 0000000..308a57a --- /dev/null +++ b/pwd.c @@ -0,0 +1,78 @@ +/* `pwd.c` - return working directory name + Copyright (c) 2022, Alan Potteiger + See `LICENSE` for copyright and license details */ + +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include + +static const char *usage = { + "usage: pwd [-L|-P]\n" +}; + +int +main(int argc, char *argv[]) +{ + char c; + char *wd, *p; + int flag; + + /* 0 == -L + 1 == -P */ + flag = 0; + + while ((c = getopt(argc, argv, "LP")) != -1) { + switch (c) { + case 'L': + flag = 0; + break; + case 'P': + flag = 1; + break; + case '?': + default: + fputs(usage, stderr); + return 1; + } + } + + if (flag) + goto pflag; + + /* -L */ + wd = getenv("PWD"); + if (wd == NULL) + goto pflag; + + /* test pathname from $PWD for ./ or ../ + if they exist, jump to the -P option */ + p = wd; + for (; *p != '\0'; p++) { + if (*p == '/') + continue; + if (*p == '.') { + if (*(p+1) == '.' && *(p+1) == '/') + goto pflag; + if (*(p+1) == '/') + goto pflag; + } + } + + printf("%s\n", wd); + return 0; + +pflag: /* -P */ + wd = getcwd(NULL, 0); + if (wd == NULL) { + perror("pwd"); + return 1; + } + + printf("%s\n", wd); + + free(wd); + return 0; +} + -- 2.11.4.GIT