diff options
Diffstat (limited to 'file.c')
| -rw-r--r-- | file.c | 81 |
1 files changed, 43 insertions, 38 deletions
| @@ -3,42 +3,47 @@ | |||
| 3 | 3 | ||
| 4 | #include "file.h" | 4 | #include "file.h" |
| 5 | 5 | ||
| 6 | struct FileContent read_entire_file(const char* file_path) { | 6 | struct FileContent read_entire_file(const char *file_path) { |
| 7 | struct FileContent file_data; | 7 | struct FileContent file_data; |
| 8 | file_data.content = NULL; | 8 | file_data.content = NULL; |
| 9 | file_data.count = 0; | 9 | file_data.count = 0; |
| 10 | 10 | ||
| 11 | FILE* file = fopen(file_path, "rb"); | 11 | FILE *file = fopen(file_path, "rb"); |
| 12 | if (file == NULL) { | 12 | if (file == NULL) { |
| 13 | perror("Error opening file"); | 13 | perror("Error opening file"); |
| 14 | return file_data; | 14 | return file_data; |
| 15 | } | 15 | } |
| 16 | 16 | ||
| 17 | fseek(file, 0, SEEK_END); | 17 | fseek(file, 0, SEEK_END); |
| 18 | long file_size = ftell(file); | 18 | long raw_size = ftell(file); |
| 19 | fseek(file, 0, SEEK_SET); | 19 | fseek(file, 0, SEEK_SET); |
| 20 | 20 | ||
| 21 | if (file_size == -1) { | 21 | if (raw_size == -1) { |
| 22 | perror("Error getting file size"); | 22 | perror("Error getting file size"); |
| 23 | return file_data; | 23 | fclose(file); |
| 24 | } | 24 | return file_data; |
| 25 | 25 | } | |
| 26 | file_data.content = (const char*)malloc(file_size); | 26 | |
| 27 | if (file_data.content == NULL) { | 27 | size_t file_size = (size_t)raw_size; |
| 28 | perror("Error allocating memory"); | 28 | char *content = (char *)malloc(file_size + 1); |
| 29 | return file_data; | 29 | if (content == NULL) { |
| 30 | } | 30 | perror("Error allocating memory"); |
| 31 | 31 | fclose(file); | |
| 32 | size_t bytes_read = fread((void*)file_data.content, 1, file_size, file); | 32 | return file_data; |
| 33 | if (bytes_read != (size_t)file_size) { | 33 | } |
| 34 | perror("Error reading file"); | 34 | |
| 35 | free((void*)file_data.content); | 35 | size_t bytes_read = fread(content, 1, file_size, file); |
| 36 | file_data.content = NULL; | 36 | if (bytes_read != file_size) { |
| 37 | return file_data; | 37 | perror("Error reading file"); |
| 38 | } | 38 | free(content); |
| 39 | 39 | fclose(file); | |
| 40 | file_data.count = bytes_read; | 40 | return file_data; |
| 41 | 41 | } | |
| 42 | fclose(file); | 42 | |
| 43 | return file_data; | 43 | content[file_size] = '\0'; |
| 44 | file_data.content = content; | ||
| 45 | file_data.count = file_size; | ||
| 46 | |||
| 47 | fclose(file); | ||
| 48 | return file_data; | ||
| 44 | } | 49 | } |
