00001
00019 #ifndef COIL_FILE_H
00020 #define COIL_FILE_H
00021
00022 #include <cstring>
00023 #include <sys/types.h>
00024 #include <dirent.h>
00025 #include <libgen.h>
00026
00027 #include <coil/config_coil.h>
00028 #include <coil/stringutil.h>
00029
00030 namespace coil
00031 {
00032
00033 inline std::string dirname(char* path)
00034 {
00035 char path_name[strlen(path)+1];
00036 strcpy(path_name, path);
00037 std::string dir_name = ::dirname(path);
00038 return dir_name;
00039 }
00040
00041 inline std::string basename(const char* path)
00042 {
00043 char path_name[strlen(path)+1];
00044 strcpy(path_name, path);
00045 std::string base_name = ::basename(path_name);
00046 return base_name;
00047 }
00048
00049 inline coil::vstring filelist(const char* path, const char* glob_str = "")
00050 {
00051 struct dirent* ent;
00052 coil::vstring flist;
00053 bool has_glob(false);
00054 std::string pattern;
00055
00056 if (path == 0) { return flist; }
00057 if (glob_str[0] != '\0') { has_glob = true; }
00058
00059 DIR* dir_ptr(::opendir(path));
00060 if (dir_ptr == 0) { return flist; }
00061
00062 while ((ent = ::readdir(dir_ptr)) != 0)
00063 {
00064 bool match(true);
00065 if (has_glob)
00066 {
00067 const char* globc(glob_str);
00068 std::string fname(ent->d_name);
00069 for (size_t i(0); i < fname.size() && globc != '\0'; ++i, ++globc)
00070 {
00071 if (*globc == '*')
00072 {
00073
00074 if (globc[1] == '\0') { break; }
00075
00076 if (globc[1] == '*' || globc[1] == '+') { --i; continue; }
00077
00078
00079 ++globc;
00080 size_t pos(fname.find(*globc, i));
00081 if (pos == std::string::npos) { match = false; break; }
00082
00083 i = pos;
00084 }
00085 else if (*globc == '+')
00086 {
00087
00088 if (globc[1] == '\0' && !(i + 1 < fname.size())) { break; }
00089
00090 if (globc[1] == '*' || globc[1] == '+') { --i; continue; }
00091
00092
00093 ++globc;
00094 size_t pos(fname.find(*globc, i + 1));
00095 if (pos == std::string::npos) { match = false; break; }
00096
00097 i = pos;
00098 }
00099 else
00100 {
00101 if (fname[i] != *globc) { match = false; }
00102 }
00103
00104
00105
00106 if (i + 1 == fname.size() &&
00107 globc[1] != '\0' && globc[1] != '*') { match = false; }
00108 }
00109 }
00110 if (match) { flist.push_back(ent->d_name); }
00111 }
00112 ::closedir(dir_ptr);
00113
00114 return flist;
00115 }
00116 };
00117
00118 #endif // COIL_FILE_H