Basic reading of files

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)
-rw-r--r-- file.c 44
-rw-r--r-- file.h 13
2 files changed, 57 insertions, 0 deletions
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
}
diff --git a/file.h b/file.h
  
1
#ifndef FILE_H
  
2
#define FILE_H
  
3
  
  
4
#include <stdio.h>
  
5
  
  
6
struct FileContent {
  
7
  const char *content;
  
8
  size_t count;
  
9
};
  
10
  
  
11
struct FileContent read_entire_file(const char *file_path);
  
12
  
  
13
#endif