+ +
efc3c5e fix(compat): define S_ISREG/S_ISDIR POSIX macros for MSVC and initialize Win32 sockets
saifmukhtar · 2026-11-24
1 /*
2 * SPDX-License-Identifier: AGPL-3.0-or-later WITH Classpath-exception-2.0
3 * Copyright (c) 2026 Saif Mukhtar
4 *
5 * OpenAVX - Open Audio-Video eXchange
6 * include/compat/win32/dirent.h - Win32 emulation of dirent.h for MSVC
7 */
8  
9 #ifndef OPENAVX_COMPAT_WIN32_DIRENT_H
10 #define OPENAVX_COMPAT_WIN32_DIRENT_H
11  
12 #if defined(__MINGW32__) || defined(__MINGW64__)
13 #include_next <dirent.h>
14 #elif defined(_MSC_VER) || defined(_WIN32)
15  
16 #ifndef WIN32_LEAN_AND_MEAN
17 #define WIN32_LEAN_AND_MEAN
18 #endif
19 #include <windows.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23  
24 struct dirent {
25 char d_name[MAX_PATH];
26 };
27  
28 typedef struct {
29 HANDLE handle;
30 WIN32_FIND_DATAA find_data;
31 struct dirent ent;
32 int first;
33 } DIR;
34  
35 static inline DIR* opendir(const char *name) {
36 if (!name) return NULL;
37 char search_path[MAX_PATH];
38 snprintf(search_path, sizeof(search_path), "%s\\*.*", name);
39 DIR *d = (DIR*)malloc(sizeof(DIR));
40 if (!d) return NULL;
41 d->handle = FindFirstFileA(search_path, &d->find_data);
42 if (d->handle == INVALID_HANDLE_VALUE) {
43 free(d);
44 return NULL;
45 }
46 d->first = 1;
47 return d;
48 }
49  
50 static inline struct dirent* readdir(DIR *d) {
51 if (!d || d->handle == INVALID_HANDLE_VALUE) return NULL;
52 if (d->first) {
53 d->first = 0;
54 strncpy(d->ent.d_name, d->find_data.cFileName, sizeof(d->ent.d_name) - 1);
55 d->ent.d_name[sizeof(d->ent.d_name) - 1] = '\0';
56 return &d->ent;
57 }
58 if (FindNextFileA(d->handle, &d->find_data)) {
59 strncpy(d->ent.d_name, d->find_data.cFileName, sizeof(d->ent.d_name) - 1);
60 d->ent.d_name[sizeof(d->ent.d_name) - 1] = '\0';
61 return &d->ent;
62 }
63 return NULL;
64 }
65  
66 static inline int closedir(DIR *d) {
67 if (!d) return -1;
68 if (d->handle != INVALID_HANDLE_VALUE) {
69 FindClose(d->handle);
70 }
71 free(d);
72 return 0;
73 }
74  
75 #ifndef S_ISREG
76 #if defined(_S_IFMT) && defined(_S_IFREG)
77 #define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
78 #elif defined(S_IFMT) && defined(S_IFREG)
79 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
80 #else
81 #define S_ISREG(m) (((m) & 0170000) == 0100000)
82 #endif
83 #endif
84  
85 #ifndef S_ISDIR
86 #if defined(_S_IFMT) && defined(_S_IFDIR)
87 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
88 #elif defined(S_IFMT) && defined(S_IFDIR)
89 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
90 #else
91 #define S_ISDIR(m) (((m) & 0170000) == 0040000)
92 #endif
93 #endif
94  
95 #endif /* __MINGW32__ vs _MSC_VER */
96  
97 #endif /* OPENAVX_COMPAT_WIN32_DIRENT_H */