forked from JeffreytheCoder/Simple-HTTP-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.c
More file actions
56 lines (49 loc) · 1.3 KB
/
file.c
File metadata and controls
56 lines (49 loc) · 1.3 KB
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
#include "file.h"
#include "compare.h"
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *get_file_extension(const char *file_name) {
const char *dot = strrchr(file_name, '.');
if (!dot || dot == file_name) {
return "";
}
return dot + 1;
}
char *get_file_case_insensitive(const char *file_name) {
DIR *dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return NULL;
}
struct dirent *entry;
char *found_file_name = NULL;
while ((entry = readdir(dir)) != NULL) {
if (case_insensitive_compare(entry->d_name, file_name)) {
found_file_name = entry->d_name;
break;
}
}
closedir(dir);
return found_file_name;
}
char *decode_url(const char *src) {
size_t src_len = strlen(src);
char *decoded = malloc(src_len + 1);
size_t decoded_len = 0;
// decode %2x to hex
for (size_t i = 0; i < src_len; i++) {
if (src[i] == '%' && i + 2 < src_len) {
int hex_val;
sscanf(src + i + 1, "%2x", &hex_val);
decoded[decoded_len++] = hex_val;
i += 2;
} else {
decoded[decoded_len++] = src[i];
}
}
// add null terminator
decoded[decoded_len] = '\0';
return decoded;
}