00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 #include <sys/types.h>
00011 #include <sys/stat.h>
00012 #include <unistd.h>
00013 #include <dirent.h>
00014 #include <wordexp.h>
00015 #include "directory.h"
00016
00017 using namespace std;
00018
00019
00020 class UnixDirectory : public Directory
00021 {
00022 public:
00023 UnixDirectory(const std::string&);
00024 virtual ~UnixDirectory();
00025
00026 virtual bool nextFile(std::string&);
00027
00028 enum {
00029 DirGood = 0,
00030 DirBad = 1
00031 };
00032
00033 private:
00034 string dirname;
00035 int status;
00036 DIR* dir;
00037 };
00038
00039
00040 UnixDirectory::UnixDirectory(const std::string& _dirname) :
00041 dirname(_dirname),
00042 status(DirGood),
00043 dir(NULL)
00044 {
00045 }
00046
00047
00048 UnixDirectory::~UnixDirectory()
00049 {
00050 if (dir != NULL)
00051 {
00052 closedir(dir);
00053 dir = NULL;
00054 }
00055 }
00056
00057
00058 bool UnixDirectory::nextFile(std::string& filename)
00059 {
00060 if (status != DirGood)
00061 return false;
00062
00063 if (dir == NULL)
00064 {
00065 dir = opendir(dirname.c_str());
00066 if (dir == NULL)
00067 {
00068 status = DirBad;
00069 return false;
00070 }
00071 }
00072
00073 struct dirent* ent = readdir(dir);
00074 if (ent == NULL)
00075 {
00076 status = DirBad;
00077 return false;
00078 }
00079 else
00080 {
00081 filename = ent->d_name;
00082 return true;
00083 }
00084 }
00085
00086
00087 Directory* OpenDirectory(const std::string& dirname)
00088 {
00089 return new UnixDirectory(dirname);
00090 }
00091
00092
00093 bool IsDirectory(const std::string& filename)
00094 {
00095 struct stat buf;
00096 stat(filename.c_str(), &buf);
00097 return S_ISDIR(buf.st_mode);
00098 }
00099
00100 std::string WordExp(const std::string& filename) {
00101 wordexp_t result;
00102 std::string expanded;
00103
00104 switch(wordexp(filename.c_str(), &result, WRDE_NOCMD)) {
00105 case 0:
00106 break;
00107 case WRDE_NOSPACE:
00108
00109
00110 wordfree(&result);
00111 default:
00112 return filename;
00113 }
00114
00115 if (result.we_wordc != 1) {
00116 wordfree(&result);
00117 return filename;
00118 }
00119
00120 expanded = result.we_wordv[0];
00121 wordfree(&result);
00122
00123 return expanded;
00124 }