00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include <dirent.h>
00022 #include <errno.h>
00023 #include <io.h>
00024 #include <stdlib.h>
00025 #include <string.h>
00026
00027 struct DIR
00028 {
00029 long handle;
00030 struct _finddata_t info;
00031 struct dirent result;
00032 char *name;
00033 };
00034
00035 DIR *opendir(const char *name)
00036 {
00037 DIR *dir = 0;
00038
00039 if(name && name[0])
00040 {
00041 size_t base_length = strlen(name);
00042 const char *all =
00043 strchr("/\\", name[base_length - 1]) ? "*" : "/*";
00044
00045 if((dir = (DIR *) malloc(sizeof *dir)) != 0 &&
00046 (dir->name = (char *) malloc(base_length + strlen(all) + 1)) != 0)
00047 {
00048 strcat(strcpy(dir->name, name), all);
00049
00050 if((dir->handle = _findfirst(dir->name, &dir->info)) != -1)
00051 {
00052 dir->result.d_name = 0;
00053 }
00054 else
00055 {
00056 free(dir->name);
00057 free(dir);
00058 dir = 0;
00059 }
00060 }
00061 else
00062 {
00063 free(dir);
00064 dir = 0;
00065 errno = ENOMEM;
00066 }
00067 }
00068 else
00069 {
00070 errno = EINVAL;
00071 }
00072
00073 return dir;
00074 }
00075
00076 int closedir(DIR *dir)
00077 {
00078 int result = -1;
00079
00080 if(dir)
00081 {
00082 if(dir->handle != -1)
00083 {
00084 result = _findclose(dir->handle);
00085 }
00086
00087 free(dir->name);
00088 free(dir);
00089 }
00090
00091 if(result == -1)
00092 {
00093 errno = EBADF;
00094 }
00095
00096 return result;
00097 }
00098
00099 struct dirent *readdir(DIR *dir)
00100 {
00101 struct dirent *result = 0;
00102
00103 if(dir && dir->handle != -1)
00104 {
00105 if(!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1)
00106 {
00107 result = &dir->result;
00108 result->d_name = dir->info.name;
00109 }
00110 }
00111 else
00112 {
00113 errno = EBADF;
00114 }
00115
00116 return result;
00117 }
00118
00119 void rewinddir(DIR *dir)
00120 {
00121 if(dir && dir->handle != -1)
00122 {
00123 _findclose(dir->handle);
00124 dir->handle = _findfirst(dir->name, &dir->info);
00125 dir->result.d_name = 0;
00126 }
00127 else
00128 {
00129 errno = EBADF;
00130 }
00131 }