best makefile
[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 for reading\n", filename));
20 FILE *fd = fopen (filename, "rb");
21 if (fd == NULL) {
22 VERBOSE (WARNING, PRINT ("Can't open file (%s) for reading\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 int len = fread (*buffer, 1, size, fd);
36 if (len != size) {
37 VERBOSE (WARNING, PRINT ("Can't read full file (%s)\n", filename));
38 }
39 fclose (fd);
40
41 (*buffer)[len] = 0;
42 return len;
43 }
44
45 /* temp name */
46
47 char *tempname (char *tempdir, char *ext)
48 {
49 char table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
50
51 unsigned int len = strlen (tempdir) + 1 + 4 + TLEN + ((ext) ? strlen (ext) : 0) + 1;
52 char *name = (char *) calloc (len, 1);
53
54 sprintf (name, "%s/tmp-", tempdir);
55 while (strlen (name) + 1 < len - ((ext) ? strlen (ext) : 0)) {
56 name[strlen (name)] = table[rand () % 64];
57 }
58 if (ext) {
59 strcat (name, ext);
60 }
61
62 return name;
63 }
64
65 /* write full file */
66
67 int writefile (char *filename, char *buffer, int size)
68 {
69
70 /* open file */
71
72 VERBOSE (DEBUG, PRINT ("Opening file %s for writing\n", filename));
73 FILE *fd = fopen (filename, "wb");
74 if (fd == NULL) {
75 VERBOSE (WARNING, PRINT ("Can't open file (%s) for writing\n", filename));
76 return -1;
77 }
78
79 /* write full file */
80
81 VERBOSE (DEBUG, PRINT ("Writing %d bytes\n", size));
82 int len = fwrite (buffer, size, 1, fd);
83 if (len != size) {
84 VERBOSE (WARNING, PRINT ("Can't write full file (%s)\n", filename));
85 }
86 fclose (fd);
87
88 return len;
89 }
90
91 /* vim: set ts=4 sw=4 et: */