1 | #include <string.h>
|
---|
2 | #include <windows.h>
|
---|
3 | #include <malloc.h>
|
---|
4 |
|
---|
5 | #include "dirent.h"
|
---|
6 |
|
---|
7 | void _getFileName(DIRSTR *dirlist, WIN32_FIND_DATA *winFileData)
|
---|
8 | {
|
---|
9 | // get leaf if directory name is given
|
---|
10 | char *leafname = strrchr(winFileData->cFileName, '\\');
|
---|
11 |
|
---|
12 | if (leafname)
|
---|
13 | {
|
---|
14 | leafname ++;
|
---|
15 | }
|
---|
16 | else
|
---|
17 | {
|
---|
18 | leafname = winFileData->cFileName;
|
---|
19 | }
|
---|
20 | strcpy(dirlist->fileData.d_name, leafname);
|
---|
21 | }
|
---|
22 |
|
---|
23 | DIRSTR *opendir(const char *name)
|
---|
24 | {
|
---|
25 | char buffer[MAX_PATH];
|
---|
26 | WIN32_FIND_DATA winFileData;
|
---|
27 | DIRSTR *newlist = (DIRSTR *) malloc(sizeof(DIRSTR));
|
---|
28 |
|
---|
29 | strcpy(buffer, name);
|
---|
30 | if (buffer[strlen(buffer)-1] != '\\')
|
---|
31 | {
|
---|
32 | strcat(buffer, "\\*");
|
---|
33 | }
|
---|
34 | else
|
---|
35 | {
|
---|
36 | strcat(buffer, "*");
|
---|
37 | }
|
---|
38 |
|
---|
39 | newlist->searchHandle = FindFirstFile(buffer, &winFileData);
|
---|
40 | if (newlist->searchHandle == INVALID_HANDLE_VALUE)
|
---|
41 | {
|
---|
42 | DWORD error = GetLastError();
|
---|
43 | if (error == ERROR_NO_MORE_FILES)
|
---|
44 | {
|
---|
45 | newlist->first = 2;
|
---|
46 | }
|
---|
47 | else
|
---|
48 | {
|
---|
49 | free(newlist);
|
---|
50 | newlist = NULL;
|
---|
51 | }
|
---|
52 | }
|
---|
53 | else
|
---|
54 | {
|
---|
55 | _getFileName(newlist, &winFileData);
|
---|
56 | newlist->first = 1;
|
---|
57 | }
|
---|
58 | return newlist;
|
---|
59 | }
|
---|
60 |
|
---|
61 | dirent *readdir(DIRSTR *dirlist)
|
---|
62 | {
|
---|
63 | if (dirlist->first == 2)
|
---|
64 | {
|
---|
65 | // empty directory
|
---|
66 | return NULL;
|
---|
67 | }
|
---|
68 | else if (dirlist->first != 1)
|
---|
69 | {
|
---|
70 | WIN32_FIND_DATA winFileData;
|
---|
71 |
|
---|
72 | if (FindNextFile(dirlist->searchHandle, &winFileData) == 0)
|
---|
73 | {
|
---|
74 | DWORD error = GetLastError();
|
---|
75 | return NULL;
|
---|
76 | }
|
---|
77 | else
|
---|
78 | {
|
---|
79 | _getFileName(dirlist, &winFileData);
|
---|
80 | }
|
---|
81 | }
|
---|
82 | else
|
---|
83 | {
|
---|
84 | dirlist->first = 0;
|
---|
85 | }
|
---|
86 |
|
---|
87 | return &dirlist->fileData;
|
---|
88 | }
|
---|
89 |
|
---|
90 | void closedir(DIRSTR *dirlist)
|
---|
91 | {
|
---|
92 | FindClose(dirlist->searchHandle);
|
---|
93 | free(dirlist);
|
---|
94 | }
|
---|