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