best makefile
[webserver.git] / file.c
CommitLineData
4baf6839
LM
1#include <malloc.h>
2#include <stdio.h>
3#include <stdlib.h>
aa628d4e 4#include <string.h>
4baf6839
LM
5
6#include "debug.h"
7
8#include "file.h"
9
aa628d4e
LM
10#define TLEN 8
11
4baf6839
LM
12/* read full file */
13
cae06547 14int readfile (char **buffer, char *filename)
4baf6839
LM
15{
16
17 /* open file */
18
6ae861c7 19 VERBOSE (DEBUG, PRINT ("Opening file %s for reading\n", filename));
4baf6839
LM
20 FILE *fd = fopen (filename, "rb");
21 if (fd == NULL) {
6ae861c7 22 VERBOSE (WARNING, PRINT ("Can't open file (%s) for reading\n", filename));
4baf6839
LM
23 return -1;
24 }
25
50c7ef81 26 VERBOSE (DEBUG, PRINT ("Seek file size\n"));
4baf6839
LM
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
50c7ef81 33 VERBOSE (DEBUG, PRINT ("Reading %d bytes\n", size));
4baf6839 34 *buffer = calloc (size + 1, 1);
0a7c57da 35 int len = fread (*buffer, 1, size, fd);
6ae861c7
LM
36 if (len != size) {
37 VERBOSE (WARNING, PRINT ("Can't read full file (%s)\n", filename));
38 }
4baf6839
LM
39 fclose (fd);
40
6ae861c7
LM
41 (*buffer)[len] = 0;
42 return len;
4baf6839
LM
43}
44
aa628d4e
LM
45/* temp name */
46
6ae861c7 47char *tempname (char *tempdir, char *ext)
aa628d4e
LM
48{
49 char table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
50
6ae861c7 51 unsigned int len = strlen (tempdir) + 1 + 4 + TLEN + ((ext) ? strlen (ext) : 0) + 1;
aa628d4e
LM
52 char *name = (char *) calloc (len, 1);
53
54 sprintf (name, "%s/tmp-", tempdir);
6ae861c7 55 while (strlen (name) + 1 < len - ((ext) ? strlen (ext) : 0)) {
aa628d4e
LM
56 name[strlen (name)] = table[rand () % 64];
57 }
6ae861c7
LM
58 if (ext) {
59 strcat (name, ext);
60 }
aa628d4e
LM
61
62 return name;
63}
64
6ae861c7
LM
65/* write full file */
66
67int 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
4baf6839 91/* vim: set ts=4 sw=4 et: */