• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017, The Android Open Source Project
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 #ifndef FILE_UTILS_H
18 #define FILE_UTILS_H
19 
20 #include <fstream>
21 #include <iostream>
22 #include <memory>
23 #include <vector>
24 
25 namespace android {
26 namespace spirit {
27 
readFile(const char * filename)28 template <typename T> std::vector<T> readFile(const char *filename) {
29   std::ifstream ifs;
30   std::filebuf *fb = ifs.rdbuf();
31   fb->open(filename, std::ios::in);
32 
33   if (!fb->is_open()) {
34     std::cerr << "failed opening " << filename << std::endl;
35     return std::vector<T>();
36   }
37 
38   ifs.seekg(0, ifs.end);
39   int length = ifs.tellg();
40   ifs.seekg(0, ifs.beg);
41 
42   std::vector<T> ret(length / sizeof(T));
43 
44   ifs.read((char *)ret.data(), length);
45 
46   fb->close();
47 
48   return ret;
49 }
50 
readFile(const std::string & filename)51 template <typename T> std::vector<T> readFile(const std::string &filename) {
52   return readFile<T>(filename.c_str());
53 }
54 
55 template <typename T>
writeFile(const char * filename,const std::vector<T> & data)56 void writeFile(const char *filename, const std::vector<T> &data) {
57   std::ofstream ofs(filename, std::ios::out);
58 
59   ofs.write(reinterpret_cast<const char *>(data.data()),
60             sizeof(T) * data.size());
61 }
62 
63 } // namespace spirit
64 } // namespace android
65 
66 #endif // FILE_UTILS_H
67