coreutils

General Software Utilities
git clone http://git.omkov.net/coreutils
Log | Tree | Refs | README | LICENCE | Download

coreutils/src/rmdir.c (67 lines, 1.6 KiB) -rw-r--r-- blame download

0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
// rmdir.c, version 1.0.1
// OMKOV coreutils implementation of POSIX rmdir
// Copyright (C) 2020, Jakob Wakeling
// MIT Licence

#include "util/error.h"
#include "util/optget.h"

#include <unistd.h>

#include <stdbool.h>
#include <stdio.h>

#define VERSION "1.0.1"

static struct lop lops[] = {
	{ "help",    ARG_NUL, 256 },
	{ "version", ARG_NUL, 257 },
	{ NULL, 0, 0 }
};

static bool pflag;

static void hlp(void);
static void ver(void);

int main(int ac, char *av[]) { A0 = av[0];
	struct opt opt = OPTGET_INIT; opt.str = "p"; opt.lops = lops;
	for (int o; (o = optget(&opt, av, 1)) != -1;) switch (o) {
	case 'p': { pflag = true; break; }
	case 256: { hlp(); return 0; }
	case 257: { ver(); return 0; }
	default: { return 1; }
	}
	
	if (opt.ind == ac) { error(1, "missing operand"); }
	
	for (char **p = &av[opt.ind]; *p; ++p) {
		if (rmdir(*p)) { warn("%s: %s", *p, serr()); continue; }
		if (pflag) {
			char *c = *p; for (; *c; ++c);
			for (--c; *p < c && *(c - 1) == '/'; --c);
			for (*c = 0; *p < c; --c) {
				if (*c != '/' || *(c - 1) == '/') { continue; }
				*c = 0; if (rmdir(*p)) { warn("%s: %s", *p, serr()); break; }
			}
		}
	}
	
	return 0;
}

static void hlp(void) {
	puts("rmdir - remove directories\n");
	puts("usage: rmdir [-p] dir...\n");
	puts("options:");
	puts("  -p         Remove all parent directories in a path");
	puts("  --help     Display help information");
	puts("  --version  Display version information");
}

static void ver(void) {
	puts("OMKOV coreutils rmdir, version " VERSION);
	puts("Copyright (C) 2020, Jakob Wakeling");
	puts("MIT Licence (https://opensource.org/licenses/MIT)");
}