add temporary directory
[webserver.git] / file.c
1 #include <malloc.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6 #include "debug.h"
7
8 #include "file.h"
9
10 #define TLEN 8
11
12 /* read full file */
13
14 int readfile (char **buffer, char *filename)
15 {
16
17 /* open file */
18
19 VERBOSE (DEBUG, PRINT ("Opening file %s\n", filename));
20 FILE *fd = fopen (filename, "rb");
21 if (fd == NULL) {
22 VERBOSE (WARNING, PRINT ("Can't open file (%s)\n", filename));
23 return -1;
24 }
25
26 VERBOSE (DEBUG, PRINT ("Seek file size\n"));
27 fseek (fd, 0, SEEK_END);
28 int size = ftell (fd);
29 fseek (fd, 0, SEEK_SET); /* same as rewind(f); */
30
31 /* read full file */
32
33 VERBOSE (DEBUG, PRINT ("Reading %d bytes\n", size));
34 *buffer = calloc (size + 1, 1);
35 fread (*buffer, size, 1, fd);
36 fclose (fd);
37
38 (*buffer)[size] = 0;
39 return size;
40 }
41
42 /* temp name */
43
44 char *tempname (char *tempdir)
45 {
46 char table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
47
48 unsigned int len = strlen (tempdir) + 1 + 4 + TLEN + 1;
49 char *name = (char *) calloc (len, 1);
50
51 sprintf (name, "%s/tmp-", tempdir);
52 while (strlen (name) + 1 < len) {
53 name[strlen (name)] = table[rand () % 64];
54 }
55
56 return name;
57 }
58
59 /* vim: set ts=4 sw=4 et: */