micro-utils/coreutils/mktemp.c

105 lines
1.7 KiB
C
Raw Permalink Normal View History

2023-10-24 20:23:32 +03:00
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
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);
2023-10-24 21:25:29 +03:00
for (size_t i = len - 1; i > 0; i--)
2023-10-24 20:23:32 +03:00
if (str[i] == 'X')
return len - i - 1;
2023-10-24 21:25:29 +03:00
return 0;
2023-10-24 20:23:32 +03:00
}
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;
}
2023-11-07 16:21:46 +03:00
int main(int argc, char **argv) {
2023-10-24 20:23:32 +03:00
unsigned int d_flag = 0;
2023-11-07 16:21:46 +03:00
char *path = NULL;
int opt;
while ((opt = getopt(argc, argv, "dp:")) != -1) {
switch (opt) {
case 'd':
d_flag = 1;
break;
case 'p':
path = optarg;
break;
default:
printf("mktemp [file]\n\t[-d Dir] [-p Base dir]\n");
return 0;
2023-10-24 20:23:32 +03:00
}
}
2023-11-07 16:21:46 +03:00
argv += optind;
argc -= optind;
if (argc == 0) {
2023-10-24 20:23:32 +03:00
fprintf(stderr, "mktemp: missing operand\n");
return 1;
}
2023-11-07 16:21:46 +03:00
if (argc > 1) {
2023-10-24 20:23:32 +03:00
fprintf(stderr, "mktemp: extra operands\n");
return 1;
}
2023-11-07 16:21:46 +03:00
if (path == NULL) {
path = getenv("TMPDIR");
if (!path || path[0] == '\0')
path = "/tmp";
}
2023-10-24 20:23:32 +03:00
if (chdir(path)) {
fprintf(stderr, "mktemp: %s\n", strerror(errno));
return 1;
}
if (d_flag) {
2023-11-07 16:21:46 +03:00
if (make_temp_dir(argv[0]))
2023-10-24 20:23:32 +03:00
return 1;
}
else {
2023-11-07 16:21:46 +03:00
if (make_temp_file(argv[0]))
2023-10-24 20:23:32 +03:00
return 1;
}
2023-11-07 16:21:46 +03:00
printf("%s/%s\n", path, argv[0]);
2023-10-24 20:23:32 +03:00
return 0;
}