sbase/mktemp.c

63 lines
1.0 KiB
C
Raw Normal View History

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