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