summaryrefslogtreecommitdiff
path: root/file_reader.c
blob: c262091928e92209d1e0c97f21b1f0cafaa235da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "file_reader.h"

#define BUFFER_SIZE 16384

File* file_open(const char* filename)
{
  File* retval = malloc(sizeof(File));
  retval->name = filename;

  FILE* file = fopen(retval->name, "rb");
  fseek(file, 0, SEEK_END);   // go to the end of the file
  if(file)
  {
    retval->size = ftell(0);  // save the position (end of the file)
    retval->data = malloc(retval->size + 1);
    fseek(file, 0, SEEK_SET); // return to the beginning of the file
    fread(retval->data, retval->size, 1, file);
    fclose(file);
    return retval; // file is completely stored in the buffer
  }
  else
  {
    perror(filename);
    return NULL;
  }
}

void file_close(File* file)
{
  if(file)
  {
    free(file->data);
    free(file);
  }
}

int main()
{
  File* file = file_open("strict.dtd");
  puts(file->data);
  file_close(file);
  return 0;
}
..