From c367d4d05fbab633bdb29ddb4795ae957785cfbd Mon Sep 17 00:00:00 2001 From: Connor Lane Smith Date: Tue, 24 May 2011 21:39:20 +0100 Subject: [PATCH] add dirname --- Makefile | 3 ++- basename.1 | 4 ++-- basename.c | 13 ++++++++----- dirname.1 | 11 +++++++++++ dirname.c | 18 ++++++++++++++++++ 5 files changed, 41 insertions(+), 8 deletions(-) create mode 100644 dirname.1 create mode 100644 dirname.c diff --git a/Makefile b/Makefile index 3640757..a7a5d84 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,8 @@ include config.mk LIB = util/enmasse.o util/eprintf.o -SRC = basename.c cat.c date.c echo.c false.c grep.c ln.c pwd.c rm.c sleep.c tee.c touch.c true.c wc.c +SRC = basename.c cat.c date.c dirname.c echo.c false.c grep.c ln.c pwd.c rm.c \ + sleep.c tee.c touch.c true.c wc.c OBJ = $(SRC:.c=.o) $(LIB) BIN = $(SRC:.c=) MAN = $(SRC:.c=.1) diff --git a/basename.1 b/basename.1 index 1dfc463..69f29db 100644 --- a/basename.1 +++ b/basename.1 @@ -1,6 +1,6 @@ .TH BASENAME 1 sbase\-VERSION .SH NAME -basename \- strip directory from filename +basename \- strip leading path component .SH SYNOPSIS .B basename .I string @@ -9,6 +9,6 @@ basename \- strip directory from filename .B basename prints the .I string -with any leading directory components, and the +with any leading path components, and the .IR suffix , removed. diff --git a/basename.c b/basename.c index 6e59db2..c29258d 100644 --- a/basename.c +++ b/basename.c @@ -3,6 +3,7 @@ #include #include #include +#include #include "util.h" int @@ -11,13 +12,15 @@ main(int argc, char *argv[]) char *s; size_t n; - if(argc < 2) + if(getopt(argc, argv, "") != -1) + exit(EXIT_FAILURE); + if(optind == argc) eprintf("usage: %s string [suffix]\n", argv[0]); - s = basename(argv[1]); - if(argc > 2 && strlen(s) > strlen(argv[2])) { - n = strlen(s) - strlen(argv[2]); - if(!strcmp(&s[n], argv[2])) + s = basename(argv[optind++]); + if(optind < argc && strlen(s) > strlen(argv[optind])) { + n = strlen(s) - strlen(argv[optind]); + if(!strcmp(&s[n], argv[optind])) s[n] = '\0'; } puts(s); diff --git a/dirname.1 b/dirname.1 new file mode 100644 index 0000000..dd45108 --- /dev/null +++ b/dirname.1 @@ -0,0 +1,11 @@ +.TH DIRNAME 1 sbase\-VERSION +.SH NAME +dirname \- strip final path component +.SH SYNOPSIS +.B dirname +.I string +.SH DESCRIPTION +.B dirname +prints the +.I string +with its final path component removed. diff --git a/dirname.c b/dirname.c new file mode 100644 index 0000000..1c08418 --- /dev/null +++ b/dirname.c @@ -0,0 +1,18 @@ +/* See LICENSE file for copyright and license details. */ +#include +#include +#include +#include +#include "util.h" + +int +main(int argc, char *argv[]) +{ + if(getopt(argc, argv, "") != -1) + exit(EXIT_FAILURE); + if(optind != argc-1) + eprintf("usage: %s string\n", argv[0]); + + puts(dirname(argv[optind])); + return EXIT_SUCCESS; +}