1 /*
2  * Copyright (C) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "dir.h"
16 
17 #if _WIN32
18 #include <windows.h>
19 #include <string>
20 struct DIR {
21     HANDLE handle;
22     WIN32_FIND_DATAA data;
23     dirent cur;
24 };
opendir(const char * path)25 DIR* opendir(const char* path)
26 {
27     DIR* d = new DIR();
28     std::string tmp = path;
29     tmp.append("\\");
30     tmp.append("*.*");
31     d->handle = FindFirstFileA(tmp.c_str(), &d->data);
32     if (d->handle == INVALID_HANDLE_VALUE) {
33         delete d;
34         return nullptr;
35     }
36     return d;
37 }
readdir(DIR * d)38 struct dirent* readdir(DIR* d)
39 {
40     if (d->data.cFileName[0] == 0) {
41         // end.
42         return nullptr;
43     }
44     strcpy(d->cur.d_name, d->data.cFileName);
45     if (d->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
46         d->cur.d_type = DT_DIR;
47     } else {
48         d->cur.d_type = DT_REG;
49     }
50     if (false == FindNextFileA(d->handle, &d->data)) {
51         // clear;
52         d->data = {};
53     }
54     return &d->cur;
55 }
closedir(DIR * d)56 void closedir(DIR* d)
57 {
58     FindClose(d->handle);
59 }
60 #else
61 #include <sys/stat.h>
62 #include <sys/types.h>
63 #include <dirent.h>
64 #include <string>
65 #endif
66