|
diff --git a/file.c b/file.c
|
|
|
1 |
#include <stdio.h> |
|
|
2 |
#include <stdlib.h> |
|
|
3 |
|
|
|
4 |
#include "file.h" |
|
|
5 |
|
|
|
6 |
struct FileContent read_entire_file(const char *file_path) { |
|
|
7 |
struct FileContent file_data; |
|
|
8 |
file_data.content = NULL; |
|
|
9 |
file_data.count = 0; |
|
|
10 |
|
|
|
11 |
FILE *file = fopen(file_path, "rb"); |
|
|
12 |
if (file == NULL) { |
|
|
13 |
perror("Error opening file"); |
|
|
14 |
return file_data; |
|
|
15 |
} |
|
|
16 |
|
|
|
17 |
fseek(file, 0, SEEK_END); |
|
|
18 |
long file_size = ftell(file); |
|
|
19 |
fseek(file, 0, SEEK_SET); |
|
|
20 |
|
|
|
21 |
if (file_size == -1) { |
|
|
22 |
perror("Error getting file size"); |
|
|
23 |
return file_data; |
|
|
24 |
} |
|
|
25 |
|
|
|
26 |
file_data.content = (const char *)malloc(file_size); |
|
|
27 |
if (file_data.content == NULL) { |
|
|
28 |
perror("Error allocating memory"); |
|
|
29 |
return file_data; |
|
|
30 |
} |
|
|
31 |
|
|
|
32 |
size_t bytes_read = fread((void *)file_data.content, 1, file_size, file); |
|
|
33 |
if (bytes_read != (size_t)file_size) { |
|
|
34 |
perror("Error reading file"); |
|
|
35 |
free((void *)file_data.content); |
|
|
36 |
file_data.content = NULL; |
|
|
37 |
return file_data; |
|
|
38 |
} |
|
|
39 |
|
|
|
40 |
file_data.count = bytes_read; |
|
|
41 |
|
|
|
42 |
fclose(file); |
|
|
43 |
return file_data; |
|
|
44 |
} |