-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_handling.c
87 lines (72 loc) · 1.77 KB
/
file_handling.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
76
77
78
79
80
81
82
83
84
85
86
87
//
// Created by lemito on 5/15/24.
//
#include "file_handling.h"
char *read_all_from_html(FILE *fd)
{
size_t bufSize, pos = 0;
char *buf, *newBuf;
fseek(fd, 0, SEEK_END);
bufSize = ftell(fd);
fseek(fd, 0, SEEK_SET);
buf = malloc(bufSize);
if (buf == NULL)
{
return NULL;
}
while (pos < bufSize)
{
size_t bytesRead = fread(buf + pos, sizeof(char), bufSize - pos, fd);
if (bytesRead == 0)
{
if (feof(fd))
{
break;
}
else
{
free(buf);
return NULL;
}
}
pos += bytesRead;
}
newBuf = realloc(buf, pos);
if (newBuf != NULL)
{
buf = newBuf;
}
return buf;
}
void send_static_file(int sockfd, const char *filename)
{
int filefd = open(filename, O_RDONLY);
if (filefd == -1)
{
perror("Ошибка открытия файла");
return;
}
char *content_type = "text/plain";
if (strstr(filename, ".css"))
content_type = CSS;
else if (strstr(filename, ".js"))
content_type = JS;
else if (strstr(filename, ".jpeg"))
content_type = JPEG;
char buffer[1024];
ssize_t bytes_read;
size_t total_bytes_read = 0;
while ((bytes_read = read(filefd, buffer, sizeof(buffer))) > 0)
{
total_bytes_read += bytes_read;
}
char *response = response_creator_static(HTTP_OK, content_type, total_bytes_read);
write_response(sockfd, response, strlen(response));
FREE_AND_NULL(response);
lseek(filefd, 0, SEEK_SET);
while ((bytes_read = read(filefd, buffer, sizeof(buffer))) > 0)
{
write_response(sockfd, buffer, bytes_read);
}
close(filefd);
}