Annotation of src/usr.bin/sdiff/common.c, Revision 1.2
1.2 ! ray 1: /* $OpenBSD: common.c,v 1.1 2006/02/20 08:38:18 otto Exp $ */
1.1 otto 2:
3: /*
4: * Written by Raymond Lai <ray@cyth.net>.
5: * Public domain.
6: */
7:
8: #include <err.h>
1.2 ! ray 9: #include <paths.h>
1.1 otto 10: #include <stdio.h>
11: #include <stdlib.h>
12: #include <unistd.h>
13:
14: #include "common.h"
15:
16: void
17: cleanup(const char *filename)
18: {
19: if (unlink(filename))
20: err(2, "could not delete: %s", filename);
21: exit(2);
22: }
23:
24: /*
25: * Creates and returns the name of a temporary file. Takes a string
26: * (or NULL) is written to the temporary file. The returned string
27: * needs to be freed.
28: */
29: char *
30: xmktemp(const char *s)
31: {
32: FILE *file;
33: int fd;
34: const char *tmpdir;
35: char *filename;
36:
1.2 ! ray 37: /* If TMPDIR is set, use it; otherwise use _PATH_TMP. */
1.1 otto 38: if (!(tmpdir = getenv("TMPDIR")))
1.2 ! ray 39: tmpdir = _PATH_TMP;
1.1 otto 40: if (asprintf(&filename, "%s/sdiff.XXXXXXXXXX", tmpdir) == -1)
41: err(2, "xmktemp");
42:
43: /* Create temp file. */
44: if ((fd = mkstemp(filename)) == -1)
45: err(2, "could not create temporary file");
46:
47: /* If we don't write anything to the file, just close. */
48: if (s == NULL) {
49: close(fd);
50:
51: return (filename);
52: }
53:
54: /* Open temp file for writing. */
55: if ((file = fdopen(fd, "w")) == NULL) {
56: warn("could not open %s", filename);
57: cleanup(filename);
58: /* NOTREACHED */
59: }
60:
61: /* Write to file. */
62: if (fputs(s, file)) {
63: warn("could not write to %s", filename);
64: cleanup(filename);
65: /* NOTREACHED */
66: }
67:
68: /* Close temp file. */
69: fclose(file);
70:
71: return (filename);
72: }