summaryrefslogtreecommitdiff
path: root/file.c
diff options
context:
space:
mode:
authorcflip <cflip@cflip.net>2023-05-30 15:56:58 -0600
committercflip <cflip@cflip.net>2023-05-30 15:56:58 -0600
commit51c9a57339b499d3c0210dac26537ca14a01f995 (patch)
tree9556e416c877cb4417fd096f8a2ef5778b673acb /file.c
parent8dbdf132ea82a567d7cef856469fd47c511b4191 (diff)
Reads from files or pipes into a buffer instead of char-by-char
This makes it possible to load image files, and doesn't spam write() as much.
Diffstat (limited to 'file.c')
-rw-r--r--file.c24
1 files changed, 13 insertions, 11 deletions
diff --git a/file.c b/file.c
index b94c071..622345f 100644
--- a/file.c
+++ b/file.c
@@ -8,6 +8,8 @@
#include <sys/stat.h>
#include <unistd.h>
+#define FILE_READBUF_SIZE 1024
+
const char *file_path_for_uri(const char *uri)
{
struct stat statbuf;
@@ -48,7 +50,10 @@ enum serve_method file_method_for_path(const char *filepath, enum http_res_code
int file_read(const char *filepath, int sockfd)
{
FILE *fp;
- char ch;
+ char buffer[FILE_READBUF_SIZE];
+ size_t bytes_read;
+
+ const char *content_type = "Content-Type: text/html\r\n\r\n";
fp = fopen(filepath, "rb");
if (fp == NULL) {
@@ -56,11 +61,9 @@ int file_read(const char *filepath, int sockfd)
return 1;
}
- write(sockfd, "Content-Type: text/html\r\n\r\n", 27);
- /* TODO: Implement a buffered read from FILE* function */
- while ((ch = fgetc(fp)) != EOF) {
- write(sockfd, &ch, 1);
- }
+ write(sockfd, content_type, strlen(content_type));
+ while ((bytes_read = fread(buffer, 1, FILE_READBUF_SIZE, fp)) > 0)
+ write(sockfd, buffer, bytes_read);
fclose(fp);
return 0;
@@ -70,7 +73,8 @@ int file_read_php(const char *filepath, int sockfd)
{
FILE *fp;
char cmdbuf[PATH_MAX];
- char ch;
+ char buffer[FILE_READBUF_SIZE];
+ size_t bytes_read;
strcpy(cmdbuf, "php-cgi ");
strcat(cmdbuf, filepath);
@@ -83,10 +87,8 @@ int file_read_php(const char *filepath, int sockfd)
return 1;
}
- /* TODO: Implement a buffered read from FILE* function */
- while ((ch = fgetc(fp)) != EOF) {
- write(sockfd, &ch, 1);
- }
+ while ((bytes_read = fread(buffer, 1, FILE_READBUF_SIZE, fp)) > 0)
+ write(sockfd, buffer, bytes_read);
pclose(fp);
return 0;