00001 #include "OSDependent/Directory.h"
00002 #include "OSDependent/OS.h"
00003
00004 Directory::Directory(const char *name) :
00005 _handle(INVALID_HANDLE_VALUE),
00006 _hasFirst(false),
00007 _isRewound(false)
00008 {
00009 strcpy(_name,name);
00010 }
00011
00012 Directory::~Directory()
00013 {
00014 close();
00015 }
00016
00017 int
00018 Directory::open()
00019 {
00020 if (_handle != INVALID_HANDLE_VALUE)
00021 return 0;
00022 char name[128];
00023
00024 strcpy(name,_name);
00025 strcat(name,"\\*");
00026
00027 WCHAR uniBuffer[512];
00028 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, name, -1, uniBuffer, 512 );
00029
00030 _handle = ::FindFirstFile(uniBuffer, &_data);
00031 if (_handle == INVALID_HANDLE_VALUE)
00032 return -1;
00033 _hasFirst = true;
00034 _isRewound = false;
00035 return 0;
00036 }
00037
00038 int
00039 Directory::close()
00040 {
00041 if (_handle == INVALID_HANDLE_VALUE)
00042 return 0;
00043 if (::FindClose(_handle) == 0)
00044 return -1;
00045 _handle = INVALID_HANDLE_VALUE;
00046 return 0;
00047 }
00048
00049 int
00050 Directory::rewind()
00051 {
00052 if (_handle == INVALID_HANDLE_VALUE)
00053 return -1;
00054 if (close() < 0)
00055 return -1;
00056 _isRewound = true;
00057 return 0;
00058 }
00059
00060 DirectoryEntry *
00061 Directory::read()
00062 {
00063 static DirectoryEntry entry;
00064 if (_isRewound) {
00065 if (open() < 0)
00066 return NULL;
00067 }
00068 if (_handle == INVALID_HANDLE_VALUE)
00069 return NULL;
00070 if (_hasFirst) {
00071 _hasFirst = false;
00072 } else if (::FindNextFile(_handle, &_data) == 0) {
00073 if (::GetLastError() == ERROR_NO_MORE_FILES) {
00074 return NULL;
00075 } else {
00076 entry.name = NULL;
00077 return &entry;
00078 }
00079 }
00080
00081 char params[256];
00082 WideCharToMultiByte(CP_ACP, 0, _data.cFileName, -1, params, 256, 0, 0);
00083
00084 entry.name = OS::strdup(params);
00085 entry.size = _data.nFileSizeLow;
00086
00087 entry.atime = 0;
00088 entry.ctime = 0;
00089 entry.mtime = 0;
00090 return &entry;
00091 }
00092
00093 int
00094 Directory::seek(int pos)
00095 {
00096 if (_isRewound) {
00097 if (open() < 0)
00098 return -1;
00099 }
00100 if (_handle == INVALID_HANDLE_VALUE)
00101 return -1;
00102 for (int i = 0; i < pos; i++) {
00103 if (::FindNextFile(_handle, &_data) == 0)
00104 return -1;
00105 }
00106 return 0;
00107 }
00108
00109 const char *
00110 Directory::name() const
00111 {
00112 return _name;
00113 }