Add file reader. Add bug that returns a smaller string than it should be.

This commit is contained in:
Rasmus Rasmussen 2025-03-10 13:20:24 +01:00
parent fbed68ebe0
commit 171195fbd6
6 changed files with 85 additions and 9 deletions

25
HTML/index.html Normal file
View File

@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hello, world!</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="description" content="" />
<link rel="icon" href="favicon.png">
</head>
<body>
<h1>Hello, world!</h1>
</body>
</html>

BIN
WebServer Executable file

Binary file not shown.

7
include/fileReader.h Normal file
View File

@ -0,0 +1,7 @@
#ifndef FILEREADER_H
#define FILEREADER_H
char *ReadHTML(char path[]);
int GetFilesize(FILE *file_ptr);
#endif

View File

@ -3,14 +3,25 @@
CC = gcc # C compiler
CFLAGS = -O2 # Compiler flags (optimization level)
main: main.o
SRC_DIR = src
BUILD_DIR = build
BIN_DIR = bin
EXECUTABLE = WebServer
# Create directories
$(shell mkdir -p $(BUILD_DIR) $(BIN_DIR))
SOURCES = $(wildcard $(SRC_DIR)/*.c)
OBJECT_FILES = $(SOURCES:$(SRC_DIR)/%.c=$(BUILD_DIR)/%.o)
$(EXECUTABLE): $(OBJECT_FILES)
$(CC) $(CFLAGS) -o $@ $^
main.o: main.c
$(CC) $(CFLAGS) -c $<
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c
$(CC) $(CFLAGS) -c $< -o $@
run:
./main
./$(EXECUTABLE)
clean:
rm -f *.o
rm -f $(BUILD_DIR)/*.o $(BIN_DIR)/*

34
src/fileReader.c Normal file
View File

@ -0,0 +1,34 @@
#include <stdio.h>
#include "../include/fileReader.h"
char *ReadHTML(char path[]) {
FILE *file_ptr = fopen(path, "r");
char file[GetFilesize(file_ptr)];
char ch;
int i = 0;
if (NULL == file_ptr) {
printf("File can't be opened \n");
}
while ((ch = fgetc(file_ptr)) != EOF) {
file[i] = ch;
i++;
}
fclose(file_ptr);
return file;
}
int GetFilesize(FILE *file_ptr) {
int prev = ftell(file_ptr);
fseek(file_ptr, 0L, SEEK_END);
int size = ftell(file_ptr);
fseek(file_ptr, prev, SEEK_SET);
return size;
}

View File

@ -1,8 +1,7 @@
#include <stdio.h>
#include "../include/fileReader.h"
int main() {
char *file = ReadHTML("/home/skingging/Documents/Projects/C/C-Webserver/HTML/index.html");
printf("Size: %d", sizeof(file));
}