]> git.sesse.net Git - nageru/blob - shared/read_file.cpp
Make Futatabi fades apply white balance.
[nageru] / shared / read_file.cpp
1 #include "shared/read_file.h"
2
3 #include <stdio.h>
4
5 using namespace std;
6
7 string read_file(const string &filename, const unsigned char *start, const size_t size)
8 {
9         FILE *fp = fopen(filename.c_str(), "r");
10         if (fp == nullptr) {
11                 // Fall back to the version we compiled in. (We prefer disk if we can,
12                 // since that makes it possible to work on shaders without recompiling
13                 // all the time.)
14                 if (start != nullptr) {
15                         return string(reinterpret_cast<const char *>(start),
16                                 reinterpret_cast<const char *>(start) + size);
17                 }
18
19                 perror(filename.c_str());
20                 abort();
21         }
22
23         int ret = fseek(fp, 0, SEEK_END);
24         if (ret == -1) {
25                 perror("fseek(SEEK_END)");
26                 abort();
27         }
28
29         int disk_size = ftell(fp);
30         if (disk_size == -1) {
31                 perror("ftell");
32                 abort();
33         }
34
35         ret = fseek(fp, 0, SEEK_SET);
36         if (ret == -1) {
37                 perror("fseek(SEEK_SET)");
38                 abort();
39         }
40
41         string str;
42         str.resize(disk_size);
43         ret = fread(&str[0], disk_size, 1, fp);
44         if (ret == -1) {
45                 perror("fread");
46                 abort();
47         }
48         if (ret == 0) {
49                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
50                         disk_size, filename.c_str());
51                 abort();
52         }
53         fclose(fp);
54
55         return str;
56 }
57