• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2005 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 #pragma once
17 
18 #include <sys/stat.h>
19 #include <time.h>
20 
21 //
22 // Handy utility functions and portability code.
23 //
24 
25 namespace android {
26 
27 /*
28  * Some utility functions for working with files.  These could be made
29  * part of a "File" class.
30  */
31 typedef enum FileType {
32     kFileTypeUnknown = 0,
33     kFileTypeNonexistent,       // i.e. ENOENT
34     kFileTypeRegular,
35     kFileTypeDirectory,
36     kFileTypeCharDev,
37     kFileTypeBlockDev,
38     kFileTypeFifo,
39     kFileTypeSymlink,
40     kFileTypeSocket,
41 } FileType;
42 /* get the file's type; follows symlinks */
43 FileType getFileType(const char* fileName);
44 
45 // MinGW doesn't support nanosecond resolution in stat() modification time, and given
46 // that it only matters on the device it's ok to keep it at a seconds level there.
47 #ifdef _WIN32
48 using ModDate = time_t;
49 inline constexpr ModDate kInvalidModDate = ModDate(-1);
50 inline constexpr unsigned long long kModDateResolutionNs = 1ull * 1000 * 1000 * 1000;
toTimeT(ModDate m)51 inline time_t toTimeT(ModDate m) {
52   return m;
53 }
54 #else
55 using ModDate = timespec;
56 inline constexpr ModDate kInvalidModDate = {-1, -1};
57 inline constexpr unsigned long long kModDateResolutionNs = 1;
toTimeT(ModDate m)58 inline time_t toTimeT(ModDate m) {
59   return m.tv_sec;
60 }
61 #endif
62 
63 /* get the file's modification date; returns kInvalidModDate w/errno set on failure */
64 ModDate getFileModDate(const char* fileName);
65 /* same, but also returns -1 if the file has already been deleted */
66 ModDate getFileModDate(int fd);
67 
68 // Extract the modification date from the stat structure.
69 ModDate getModDate(const struct ::stat& st);
70 
71 // Check if |path| or |fd| resides on a readonly filesystem.
72 bool isReadonlyFilesystem(const char* path);
73 bool isReadonlyFilesystem(int fd);
74 
75 bool isKnownWritablePath(const char* path);
76 
77 }  // namespace android
78 
79 // Whoever uses getFileModDate() will need this as well
80 inline bool operator==(const timespec& l, const timespec& r) {
81   return l.tv_sec == r.tv_sec && l.tv_nsec == r.tv_nsec;
82 }
83