-
Notifications
You must be signed in to change notification settings - Fork 0
/
readfile.h
46 lines (40 loc) · 1.16 KB
/
readfile.h
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
44
45
46
#include <stdio.h>
#include <stdlib.h>
///////////////////////////////////////////////////////////
// Read File
///////////////////////////////////////////////////////////
char *readFile(char *input)
{
char *source = NULL;
FILE *fp = fopen(input, "r");
if (fp != NULL)
{
/* Go to the end of the file. */
if (fseek(fp, 0L, SEEK_END) == 0)
{
/* Get the size of the file. */
long bufsize = ftell(fp);
if (bufsize == -1)
{ /* Error */
}
/* Allocate our buffer to that size. */
source = malloc(sizeof(char) * (bufsize + 1));
/* Go back to the start of the file. */
if (fseek(fp, 0L, SEEK_SET) != 0)
{ /* Error */
}
/* Read the entire file into memory. */
size_t newLen = fread(source, sizeof(char), bufsize, fp);
if (ferror(fp) != 0)
{
fputs("Error reading file", stderr);
}
else
{
source[newLen++] = '\0'; /* Just to be safe. */
}
}
fclose(fp);
}
return source;
}