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/libs/utils/files.h" 18 19 #include <glog/logging.h> 20 21 #include <array> 22 #include <climits> 23 #include <cstdio> 24 #include <cstdlib> 25 #include <sys/types.h> 26 #include <sys/stat.h> 27 #include <unistd.h> 28 29 namespace cvd { 30 FileExists(const std::string & path)31bool FileExists(const std::string& path) { 32 struct stat st; 33 return stat(path.c_str(), &st) == 0; 34 } 35 FileHasContent(const std::string & path)36bool FileHasContent(const std::string& path) { 37 return FileSize(path) > 0; 38 } 39 DirectoryExists(const std::string & path)40bool DirectoryExists(const std::string& path) { 41 struct stat st; 42 if (stat(path.c_str(), &st) == -1) { 43 return false; 44 } 45 if ((st.st_mode & S_IFMT) != S_IFDIR) { 46 return false; 47 } 48 return true; 49 } 50 AbsolutePath(const std::string & path)51std::string AbsolutePath(const std::string& path) { 52 if (path.empty()) { 53 return {}; 54 } 55 if (path[0] == '/') { 56 return path; 57 } 58 59 std::array<char, PATH_MAX> buffer{}; 60 if (!realpath(".", buffer.data())) { 61 LOG(WARNING) << "Could not get real path for current directory \".\"" 62 << ": " << strerror(errno); 63 return {}; 64 } 65 return std::string{buffer.data()} + "/" + path; 66 } 67 FileSize(const std::string & path)68off_t FileSize(const std::string& path) { 69 struct stat st; 70 if (stat(path.c_str(), &st) == -1) { 71 return 0; 72 } 73 return st.st_size; 74 } 75 RemoveFile(const std::string & file)76bool RemoveFile(const std::string& file) { 77 LOG(INFO) << "Removing " << file; 78 return remove(file.c_str()) == 0; 79 } 80 81 } // namespace cvd 82