diff options
author | David Oberhollenzer <david.oberhollenzer@sigma-star.at> | 2019-10-07 14:56:09 +0200 |
---|---|---|
committer | David Oberhollenzer <david.oberhollenzer@sigma-star.at> | 2019-10-07 14:59:03 +0200 |
commit | 145dfce5f04a3a74a49cc016f15b0aa6d9996662 (patch) | |
tree | 919357d5a18934222741732c8444db7711421aa3 /lib/common/dirstack.c | |
parent | 7e1be3986b3b8229f0162431b6e02c24e04a5dba (diff) |
Cleanup: move directory handling code to libcommon
Signed-off-by: David Oberhollenzer <david.oberhollenzer@sigma-star.at>
Diffstat (limited to 'lib/common/dirstack.c')
-rw-r--r-- | lib/common/dirstack.c | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/lib/common/dirstack.c b/lib/common/dirstack.c new file mode 100644 index 0000000..8f73898 --- /dev/null +++ b/lib/common/dirstack.c @@ -0,0 +1,77 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* + * dirstack.c + * + * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at> + */ +#include "common.h" + +#include <string.h> +#include <stdlib.h> +#include <unistd.h> +#include <assert.h> +#include <fcntl.h> +#include <stdio.h> + +#define STACK_DEPTH 128 + +static int dirstack[STACK_DEPTH]; +static int stacktop = 0; + +int pushd(const char *path) +{ + int fd; + + assert(stacktop < STACK_DEPTH); + + fd = open(".", O_DIRECTORY | O_PATH | O_RDONLY | O_CLOEXEC); + + if (fd < 0) { + perror("open ./"); + return -1; + } + + if (chdir(path)) { + perror(path); + close(fd); + return -1; + } + + dirstack[stacktop++] = fd; + return 0; +} + +int pushdn(const char *path, size_t len) +{ + char *temp; + int ret; + + temp = strndup(path, len); + if (temp == NULL) { + perror("pushd"); + return -1; + } + + ret = pushd(temp); + + free(temp); + return ret; +} + +int popd(void) +{ + int fd; + + assert(stacktop > 0); + + fd = dirstack[stacktop - 1]; + + if (fchdir(fd)) { + perror("popd"); + return -1; + } + + --stacktop; + close(fd); + return 0; +} |