add dirname

This commit is contained in:
Connor Lane Smith 2011-05-24 21:39:20 +01:00
parent 4fc1ad22ad
commit c367d4d05f
5 changed files with 41 additions and 8 deletions

View File

@ -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)

View File

@ -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.

View File

@ -3,6 +3,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#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);

11
dirname.1 Normal file
View File

@ -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.

18
dirname.c Normal file
View File

@ -0,0 +1,18 @@
/* See LICENSE file for copyright and license details. */
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#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;
}