From a2fae4ab76941c59b8a60d4cbba46f7ae346a69d Mon Sep 17 00:00:00 2001 From: Your Name Date: Tue, 24 Oct 2023 20:23:32 +0300 Subject: [PATCH] mktemp --- TODO | 3 +- coreutils/mktemp.c | 94 ++++++++++++++++++++++++++++++++++++++++++++++ coreutils/rm.c | 5 ++- 3 files changed, 98 insertions(+), 4 deletions(-) create mode 100644 coreutils/mktemp.c diff --git a/TODO b/TODO index c9d93d2..de5b049 100644 --- a/TODO +++ b/TODO @@ -1,8 +1,6 @@ With "micro-" prefix *Todo: -mktemp -ln nice renice nohup @@ -12,6 +10,7 @@ split truncate date tee +ln tr cut shuf diff --git a/coreutils/mktemp.c b/coreutils/mktemp.c new file mode 100644 index 0000000..89626a1 --- /dev/null +++ b/coreutils/mktemp.c @@ -0,0 +1,94 @@ +#include +#include +#include +#include +#include + +int make_temp_dir(char *tmp) { + if (!mkdtemp(tmp)) { + if (errno == EINVAL) + fprintf(stderr, "mktemp: template does not end in exactly 'XXXXX': %s\n", tmp); + + else + fprintf(stderr, "mktemp: %s\n", strerror(errno)); + + return 1; + } + + return 0; +} + +int get_suffix(const char *str) { + size_t len = strlen(str); + for (size_t i = len - 1; i >= 0; i--) + if (str[i] == 'X') + return len - i - 1; + + exit(1); +} + +int make_temp_file(char *tmp) { + if (!strstr(tmp, "XXXXXX")) { + fprintf(stderr, "mktemp: too few X's in template: %s\n", tmp); + return 1; + } + + int fd = mkstemps(tmp, get_suffix(tmp)); + if (fd < 0) { + fprintf(stderr, "mktemp: %s\n", strerror(errno)); + return 1; + } + + close(fd); + return 0; +} + +int main(const int argc, char **argv) { + unsigned int d_flag = 0; + + int i; + for (i = 1; i < argc; i++) { + if (argv[i][0] != '-') + break; + + else if (!strcmp(argv[i], "-d")) + d_flag = 1; + + else if (!strcmp(argv[i], "--help")) { + printf("mktemp [-d] [file]\n"); + return 0; + } + } + + if (argc - i == 0) { + fprintf(stderr, "mktemp: missing operand\n"); + return 1; + } + + if (argc - 1 > i) { + fprintf(stderr, "mktemp: extra operands\n"); + return 1; + } + + char *path = getenv("TMPDIR"); + if (!path || path[0] == '\0') + path = "/tmp"; + + if (chdir(path)) { + fprintf(stderr, "mktemp: %s\n", strerror(errno)); + return 1; + } + + if (d_flag) { + if (make_temp_dir(argv[i])) + return 1; + } + + else { + if (make_temp_file(argv[i])) + return 1; + } + + printf("%s/%s\n", path, argv[i]); + return 0; +} diff --git a/coreutils/rm.c b/coreutils/rm.c index f513c5a..cfaddc0 100644 --- a/coreutils/rm.c +++ b/coreutils/rm.c @@ -64,15 +64,16 @@ int main(const int argc, char **argv) { return 0; } + int status = 0; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') continue; int status = rmtree(argv[i]); if (status != 0) - return status; + status = 1; } - return 0; + return status; }