first http server working
[webserver.git] / file.c
1 #include <malloc.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 #include "debug.h"
6
7 #include "file.h"
8
9 /* read full file */
10
11 int readfile (char **buffer, char *filename)
12 {
13
14 /* open file */
15
16 VERBOSE (DEBUG, PRINT ("Opening file %s\n", filename));
17 FILE *fd = fopen (filename, "rb");
18 if (fd == NULL) {
19 VERBOSE (WARNING, PRINT ("Can't open file (%s)\n", filename));
20 return -1;
21 }
22
23 VERBOSE (DEBUG, PRINT ("Seek file size\n"));
24 fseek (fd, 0, SEEK_END);
25 int size = ftell (fd);
26 fseek (fd, 0, SEEK_SET); /* same as rewind(f); */
27
28 /* read full file */
29
30 VERBOSE (DEBUG, PRINT ("Reading %d bytes\n", size));
31 *buffer = calloc (size + 1, 1);
32 fread (*buffer, size, 1, fd);
33 fclose (fd);
34
35 (*buffer)[size] = 0;
36 return size;
37 }
38
39 /* vim: set ts=4 sw=4 et: */