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)31 bool FileExists(const std::string& path) {
32 struct stat st;
33 return stat(path.c_str(), &st) == 0;
34 }
35
FileHasContent(const std::string & path)36 bool FileHasContent(const std::string& path) {
37 return FileSize(path) > 0;
38 }
39
DirectoryExists(const std::string & path)40 bool 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)51 std::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)68 off_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
76 // TODO(schuffelen): Use std::filesystem::last_write_time when on C++17
FileModificationTime(const std::string & path)77 std::chrono::system_clock::time_point FileModificationTime(const std::string& path) {
78 struct stat st;
79 if (stat(path.c_str(), &st) == -1) {
80 return std::chrono::system_clock::time_point();
81 }
82 std::chrono::seconds seconds(st.st_mtim.tv_sec);
83 return std::chrono::system_clock::time_point(seconds);
84 }
85
RemoveFile(const std::string & file)86 bool RemoveFile(const std::string& file) {
87 LOG(INFO) << "Removing " << file;
88 return remove(file.c_str()) == 0;
89 }
90
CurrentDirectory()91 std::string CurrentDirectory() {
92 char* path = getcwd(nullptr, 0);
93 std::string ret(path);
94 free(path);
95 return ret;
96 }
97
98 } // namespace cvd
99