2 * Copyright 2016 Google Inc. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "flatbuffers/util.h"
19 namespace flatbuffers {
21 bool FileExistsRaw(const char *name) {
22 std::ifstream ifs(name);
26 bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
27 std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
28 if (!ifs.is_open()) return false;
30 // The fastest way to read a file into a string.
31 ifs.seekg(0, std::ios::end);
32 (*buf).resize(static_cast<size_t>(ifs.tellg()));
33 ifs.seekg(0, std::ios::beg);
34 ifs.read(&(*buf)[0], (*buf).size());
36 // This is slower, but works correctly on all platforms for text files.
37 std::ostringstream oss;
44 static LoadFileFunction g_load_file_function = LoadFileRaw;
45 static FileExistsFunction g_file_exists_function = FileExistsRaw;
47 bool LoadFile(const char *name, bool binary, std::string *buf) {
48 assert(g_load_file_function);
49 return g_load_file_function(name, binary, buf);
52 bool FileExists(const char *name) {
53 assert(g_file_exists_function);
54 return g_file_exists_function(name);
57 LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
58 LoadFileFunction previous_function = g_load_file_function;
59 g_load_file_function = load_file_function ? load_file_function : LoadFileRaw;
60 return previous_function;
63 FileExistsFunction SetFileExistsFunction(
64 FileExistsFunction file_exists_function) {
65 FileExistsFunction previous_function = g_file_exists_function;
66 g_file_exists_function = file_exists_function ?
67 file_exists_function : FileExistsRaw;
68 return previous_function;
71 } // namespace flatbuffers