diff options
| author | Mitja Felicijan <mitja.felicijan@gmail.com> | 2023-11-08 23:53:20 +0100 |
|---|---|---|
| committer | Mitja Felicijan <mitja.felicijan@gmail.com> | 2023-11-08 23:53:20 +0100 |
| commit | 2d1cfb1f1c90fe4cbd2eec4da79484f8727dd670 (patch) | |
| tree | 7ea956b53e632b915388d8ef44fa560326a9c30a | |
| parent | f71732e188c847cd92d83f94902d57d0ed4d42fb (diff) | |
| download | crep-2d1cfb1f1c90fe4cbd2eec4da79484f8727dd670.tar.gz | |
Basic reading of files
| -rw-r--r-- | file.c | 44 | ||||
| -rw-r--r-- | file.h | 13 |
2 files changed, 57 insertions, 0 deletions
@@ -0,0 +1,44 @@ +#include <stdio.h> +#include <stdlib.h> + +#include "file.h" + +struct FileContent read_entire_file(const char *file_path) { + struct FileContent file_data; + file_data.content = NULL; + file_data.count = 0; + + FILE *file = fopen(file_path, "rb"); + if (file == NULL) { + perror("Error opening file"); + return file_data; + } + + fseek(file, 0, SEEK_END); + long file_size = ftell(file); + fseek(file, 0, SEEK_SET); + + if (file_size == -1) { + perror("Error getting file size"); + return file_data; + } + + file_data.content = (const char *)malloc(file_size); + if (file_data.content == NULL) { + perror("Error allocating memory"); + return file_data; + } + + size_t bytes_read = fread((void *)file_data.content, 1, file_size, file); + if (bytes_read != (size_t)file_size) { + perror("Error reading file"); + free((void *)file_data.content); + file_data.content = NULL; + return file_data; + } + + file_data.count = bytes_read; + + fclose(file); + return file_data; +} @@ -0,0 +1,13 @@ +#ifndef FILE_H +#define FILE_H + +#include <stdio.h> + +struct FileContent { + const char *content; + size_t count; +}; + +struct FileContent read_entire_file(const char *file_path); + +#endif |
