forked from bloominstituteoftechnology/C-Web-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.c
75 lines (61 loc) · 1.51 KB
/
file.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "file.h"
/**
* Loads a file into memory and returns a pointer to the data.
*
* Buffer is not NUL-terminated.
*/
struct file_data *file_load(char *filename)
{
char *buffer, *p;
struct stat buf;
int bytes_read, bytes_remaining, total_bytes = 0;
// Get the file size
if (stat(filename, &buf) == -1) {
return NULL;
}
// Make sure it's a regular file
if (!(buf.st_mode & S_IFREG)) {
return NULL;
}
// Open the file for reading
FILE *fp = fopen(filename, "rb");
if (fp == NULL) {
return NULL;
}
// Allocate that many bytes
bytes_remaining = buf.st_size;
p = buffer = malloc(bytes_remaining);
if (buffer == NULL) {
return NULL;
}
// Read in the entire file
while (bytes_read = fread(p, 1, bytes_remaining, fp), bytes_read != 0 && bytes_remaining > 0) {
if (bytes_read == -1) {
free(buffer);
return NULL;
}
bytes_remaining -= bytes_read;
p += bytes_read;
total_bytes += bytes_read;
}
// Allocate the file data struct
struct file_data *filedata = malloc(sizeof *filedata);
if (filedata == NULL) {
free(buffer);
return NULL;
}
filedata->data = buffer;
filedata->size = total_bytes;
return filedata;
}
/**
* Frees memory allocated by file_load().
*/
void file_free(struct file_data *filedata)
{
free(filedata->data);
free(filedata);
}