]> mj.ucw.cz Git - libucw.git/blob - lib/temp.c
Moved #include <getopt.h> to conf.h.
[libucw.git] / lib / temp.c
1 /*
2  *      Sherlock Library -- Temporary Files
3  *
4  *      (c) 1997 Martin Mares <mj@ucw.cz>
5  */
6
7 #include "lib/lib.h"
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <fcntl.h>
12 #include <unistd.h>
13
14 u32
15 temprand(uns key)
16 {
17   static int seeded = 0;
18   u32 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 }