• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 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 #include "common/file-utils.h"
18 
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 
24 #include <fstream>
25 #include <memory>
26 #include <string>
27 
28 #include "util/base/logging.h"
29 
30 namespace libtextclassifier {
31 namespace nlp_core {
32 
33 namespace file_utils {
34 
GetFileContent(const std::string & filename,std::string * content)35 bool GetFileContent(const std::string &filename, std::string *content) {
36   std::ifstream input_stream(filename, std::ifstream::binary);
37   if (input_stream.fail()) {
38     TC_LOG(INFO) << "Error opening " << filename;
39     return false;
40   }
41 
42   content->assign(
43       std::istreambuf_iterator<char>(input_stream),
44       std::istreambuf_iterator<char>());
45 
46   if (input_stream.fail()) {
47     TC_LOG(ERROR) << "Error reading " << filename;
48     return false;
49   }
50 
51   TC_LOG(INFO) << "Successfully read " << filename;
52   return true;
53 }
54 
FileExists(const std::string & filename)55 bool FileExists(const std::string &filename) {
56   struct stat s = {0};
57   if (!stat(filename.c_str(), &s)) {
58     return s.st_mode & S_IFREG;
59   } else {
60     return false;
61   }
62 }
63 
DirectoryExists(const std::string & dirpath)64 bool DirectoryExists(const std::string &dirpath) {
65   struct stat s = {0};
66   if (!stat(dirpath.c_str(), &s)) {
67     return s.st_mode & S_IFDIR;
68   } else {
69     return false;
70   }
71 }
72 
73 }  // namespace file_utils
74 
75 }  // namespace nlp_core
76 }  // namespace libtextclassifier
77