sbase/mktemp.c

70 lines
1.1 KiB
C
Raw Normal View History

2013-11-12 06:52:28 -05:00
/* See LICENSE file for copyright and license details. */
#include <libgen.h>
2013-11-12 06:52:28 -05:00
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
2013-11-12 06:52:28 -05:00
#include "util.h"
static void
usage(void)
{
2013-11-13 07:10:49 -05:00
eprintf("usage: %s [-dq] [template]\n", argv0);
2013-11-12 06:52:28 -05:00
}
int
main(int argc, char *argv[])
{
int dflag = 0, qflag = 0, fd;
char *template = "tmp.XXXXXXXXXX",
*tmpdir = "/tmp", *p,
path[PATH_MAX], tmp[PATH_MAX];
2013-11-12 06:52:28 -05:00
ARGBEGIN {
case 'd':
dflag = 1;
break;
2013-11-13 07:10:49 -05:00
case 'q':
qflag = 1;
break;
2013-11-12 06:52:28 -05:00
default:
usage();
} ARGEND;
if (argc > 1)
usage();
else if (argc == 1)
template = argv[0];
2013-11-14 14:46:21 -05:00
if ((p = getenv("TMPDIR")))
tmpdir = p;
estrlcpy(tmp, template, sizeof(tmp));
p = dirname(tmp);
if (p[0] != '.') {
estrlcpy(path, template, sizeof(path));
} else {
estrlcpy(path, tmpdir, sizeof(path));
estrlcat(path, "/", sizeof(path));
estrlcat(path, template, sizeof(path));
}
2013-11-12 06:52:28 -05:00
if (dflag) {
if (!mkdtemp(path)) {
2013-11-13 07:10:49 -05:00
if (!qflag)
eprintf("mkdtemp %s:", path);
return 1;
2013-11-13 07:10:49 -05:00
}
2013-11-12 06:52:28 -05:00
} else {
if ((fd = mkstemp(path)) < 0) {
2013-11-13 07:10:49 -05:00
if (!qflag)
eprintf("mkstemp %s:", path);
return 1;
2013-11-13 07:10:49 -05:00
}
2013-11-12 06:52:28 -05:00
close(fd);
}
puts(path);
2014-10-02 18:46:04 -04:00
return 0;
2013-11-12 06:52:28 -05:00
}