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 if (DirExists(name)) return false;
28 std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
29 if (!ifs.is_open()) return false;
31 // The fastest way to read a file into a string.
32 ifs.seekg(0, std::ios::end);
33 auto size = ifs.tellg();
34 (*buf).resize(static_cast<size_t>(size));
35 ifs.seekg(0, std::ios::beg);
36 ifs.read(&(*buf)[0], (*buf).size());
38 // This is slower, but works correctly on all platforms for text files.
39 std::ostringstream oss;
46 static LoadFileFunction g_load_file_function = LoadFileRaw;
47 static FileExistsFunction g_file_exists_function = FileExistsRaw;
49 bool LoadFile(const char *name, bool binary, std::string *buf) {
50 assert(g_load_file_function);
51 return g_load_file_function(name, binary, buf);
54 bool FileExists(const char *name) {
55 assert(g_file_exists_function);
56 return g_file_exists_function(name);
59 bool DirExists(const char *name) {
61 #define flatbuffers_stat _stat
62 #define FLATBUFFERS_S_IFDIR _S_IFDIR
64 #define flatbuffers_stat stat
65 #define FLATBUFFERS_S_IFDIR S_IFDIR
67 struct flatbuffers_stat file_info;
68 if (flatbuffers_stat(name, &file_info) != 0) return false;
69 return (file_info.st_mode & FLATBUFFERS_S_IFDIR) != 0;
72 LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
73 LoadFileFunction previous_function = g_load_file_function;
74 g_load_file_function = load_file_function ? load_file_function : LoadFileRaw;
75 return previous_function;
78 FileExistsFunction SetFileExistsFunction(
79 FileExistsFunction file_exists_function) {
80 FileExistsFunction previous_function = g_file_exists_function;
81 g_file_exists_function = file_exists_function ?
82 file_exists_function : FileExistsRaw;
83 return previous_function;
86 } // namespace flatbuffers