summaryrefslogtreecommitdiff
path: root/usr.bin/sdiff/common.c
blob: b814ccbbad9e6915e873f7dbcde339080006c8f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*	$OpenBSD: common.c,v 1.2 2006/03/11 07:12:42 ray Exp $	*/

/*
 * Written by Raymond Lai <ray@cyth.net>.
 * Public domain.
 */

#include <err.h>
#include <paths.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "common.h"

void
cleanup(const char *filename)
{
	if (unlink(filename))
		err(2, "could not delete: %s", filename);
	exit(2);
}

/*
 * Creates and returns the name of a temporary file.  Takes a string
 * (or NULL) is written to the temporary file.  The returned string
 * needs to be freed.
 */
char *
xmktemp(const char *s)
{
	FILE *file;
	int fd;
	const char *tmpdir;
	char *filename;

	/* If TMPDIR is set, use it; otherwise use _PATH_TMP. */
	if (!(tmpdir = getenv("TMPDIR")))
		tmpdir = _PATH_TMP;
	if (asprintf(&filename, "%s/sdiff.XXXXXXXXXX", tmpdir) == -1)
		err(2, "xmktemp");

	/* Create temp file. */
	if ((fd = mkstemp(filename)) == -1)
		err(2, "could not create temporary file");

	/* If we don't write anything to the file, just close. */
	if (s == NULL) {
		close(fd);

		return (filename);
	}

	/* Open temp file for writing. */
	if ((file = fdopen(fd, "w")) == NULL) {
		warn("could not open %s", filename);
		cleanup(filename);
		/* NOTREACHED */
	}

	/* Write to file. */
	if (fputs(s, file)) {
		warn("could not write to %s", filename);
		cleanup(filename);
		/* NOTREACHED */
	}

	/* Close temp file. */
	fclose(file);

	return (filename);
}