]> mj.ucw.cz Git - libucw.git/blob - lib/temp.c
32a6529bca724795aa2f34c4c3d51000cbf74ee9
[libucw.git] / lib / temp.c
1 /*
2  *      Sherlock Library -- Temporary Files
3  *
4  *      (c) 1997 Martin Mares, <mj@atrey.karlin.mff.cuni.cz>
5  */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11
12 #include "lib.h"
13
14 ulg
15 temprand(uns key)
16 {
17   static int seeded = 0;
18   ulg rand;
19
20   if (!seeded)
21     {
22       seeded = 1;
23       srand(getpid());
24     }
25   rand = random() << 1;
26   rand += key * 0xdeadbeef;
27   return rand;
28 }
29
30 void
31 open_temp(struct tempfile *tf, byte *tftype)
32 {
33   int retry = 50;
34   while (retry--)
35     {
36       sprintf(tf->name, TMP_DIR "/%s%08x", tftype, temprand(retry));
37       tf->fh = open(tf->name, O_RDWR | O_CREAT | O_EXCL, 0666);
38       if (tf->fh >= 0)
39         return;
40     }
41   die("Unable to create temporary file");
42 }
43
44 void
45 delete_temp(struct tempfile *tf)
46 {
47   close(tf->fh);
48   unlink(tf->name);
49 }