blob: 85c7ef70a465d042827f3506f5d55880b596d4f1 [file] [log] [blame]
Jorge E. Moreira02f464c2018-07-06 11:30:34 -07001/*
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
Ryan Haining10e42312018-07-17 12:11:52 -070019#include <glog/logging.h>
20
21#include <array>
22#include <climits>
23#include <cstdlib>
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070024#include <sys/types.h>
25#include <sys/stat.h>
26#include <unistd.h>
27
28namespace cvd {
29
30bool FileHasContent(const std::string& path) {
31 struct stat st;
Ryan Haining10e42312018-07-17 12:11:52 -070032 if (stat(path.c_str(), &st) == -1) {
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070033 return false;
Ryan Haining10e42312018-07-17 12:11:52 -070034 }
35 if (st.st_size == 0) {
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070036 return false;
Ryan Haining10e42312018-07-17 12:11:52 -070037 }
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070038 return true;
39}
40
41bool DirectoryExists(const std::string& path) {
42 struct stat st;
Ryan Haining10e42312018-07-17 12:11:52 -070043 if (stat(path.c_str(), &st) == -1) {
44 return false;
45 }
46 if ((st.st_mode & S_IFMT) != S_IFDIR) {
47 return false;
48 }
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070049 return true;
50}
Ryan Haining10e42312018-07-17 12:11:52 -070051
52std::string RealPath(const std::string& path) {
53 std::array<char, PATH_MAX> buffer{};
54 if (!realpath(path.c_str(), buffer.data())) {
55 LOG(WARNING) << "Could not get real path for file " << path << ": "
56 << strerror(errno);
57 return {};
58 }
59 return {buffer.data()};
60}
61
Jorge E. Moreira02f464c2018-07-06 11:30:34 -070062} // namespace cvd