00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039 #include <errno.h>
00040 #include <sys/stat.h>
00041 #include <sys/types.h>
00042 #include <dirent.h>
00043
00044 #include "debug/Log.h"
00045 #include "FileUtils.h"
00046
00047 namespace oasys {
00048
00049 bool
00050 FileUtils::readable(const char* path, const char* log)
00051 {
00052 struct stat st;
00053 int ret = stat(path, &st);
00054
00055 if (ret == -1) {
00056 logf(log, LOG_DEBUG,
00057 "FileUtils::readable(%s): error running stat %s",
00058 path, strerror(errno));
00059 return false;
00060 }
00061
00062 if (!S_ISREG(st.st_mode)) {
00063 logf(log, LOG_DEBUG,
00064 "FileUtils::readable(%s): not a regular file", path);
00065 return false;
00066 }
00067
00068 if (st.st_mode & S_IRUSR == 0) {
00069 logf(log, LOG_DEBUG,
00070 "FileUtils::readable(%s): no readable permissions", path);
00071 return false;
00072 }
00073
00074 return true;
00075 }
00076
00077 size_t
00078 FileUtils::size(const char* path, const char* log)
00079 {
00080 struct stat st;
00081 int ret = stat(path, &st);
00082
00083 if (ret == -1) {
00084 if (log) {
00085 logf(log, LOG_DEBUG,
00086 "FileUtils::size(%s): error running stat %s",
00087 path, strerror(errno));
00088 }
00089 return 0;
00090 }
00091
00092 if (!S_ISREG(st.st_mode)) {
00093 if (log) {
00094 logf(log, LOG_DEBUG,
00095 "FileUtils::size(%s): not a regular file", path);
00096 }
00097 return 0;
00098 }
00099
00100 return st.st_size;
00101 }
00102
00103 void
00104 FileUtils::abspath(std::string* path)
00105 {
00106 if ((*path)[0] != '/') {
00107 char cwd[PATH_MAX];
00108 ::getcwd(cwd, PATH_MAX);
00109
00110 std::string temp = *path;
00111 *path = cwd;
00112 *path += '/' + temp;
00113 }
00114 }
00115
00116 int
00117 FileUtils::rm_all_from_dir(const char* path)
00118 {
00119 DIR* dir = opendir(path);
00120
00121 if (dir == 0) {
00122 return errno;
00123 }
00124
00125 struct dirent* ent = readdir(dir);
00126 if (ent == 0) {
00127 return errno;
00128 }
00129
00130 while (ent != 0) {
00131 std::string ent_name(path);
00132 ent_name = ent_name + "/" + ent->d_name;
00133 int err = unlink(ent_name.c_str());
00134 ASSERT(err != 0);
00135
00136 ent = readdir(dir);
00137 }
00138
00139 closedir(dir);
00140
00141 return 0;
00142 }
00143
00144
00145 }