2 * dirent.h - dirent API for Microsoft Visual Studio
4 * Copyright (C) 2006-2012 Toni Ronkko
5 * Modified by Leonardo Florez-Valencia (florez-l@javeriana.edu.co)
7 * Permission is hereby granted, free of charge, to any person obtaining
8 * a copy of this software and associated documentation files (the
9 * ``Software''), to deal in the Software without restriction, including
10 * without limitation the rights to use, copy, modify, merge, publish,
11 * distribute, sublicense, and/or sell copies of the Software, and to
12 * permit persons to whom the Software is furnished to do so, subject to
13 * the following conditions:
15 * The above copyright notice and this permission notice shall be included
16 * in all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21 * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR
22 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 * OTHER DEALINGS IN THE SOFTWARE.
26 * $Id: dirent.h,v 1.20 2014/03/19 17:52:23 tronkko Exp $
28 #ifndef __cpPlugins__dirent__h__
29 #define __cpPlugins__dirent__h__
31 // florez-l: use this file in windows environments
32 #if defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ )
34 * Define architecture flags so we don't need to include windows.h.
35 * Avoiding windows.h makes it simpler to use windows sockets in conjunction
38 #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_IX86)
41 #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_AMD64)
53 #include <sys/types.h>
57 /* Indicates that d_type field is available in dirent structure */
58 #define ___cpPlugins__dirent__h__AVE_D_TYPE
60 /* Indicates that d_namlen field is available in dirent structure */
61 #define ___cpPlugins__dirent__h__AVE_D_NAMLEN
63 /* Entries missing from MSVC 6.0 */
64 #if !defined(FILE_ATTRIBUTE_DEVICE)
65 # define FILE_ATTRIBUTE_DEVICE 0x40
68 /* File type and permission flags for stat() */
70 # define S_IFMT _S_IFMT /* File type mask */
73 # define S_IFDIR _S_IFDIR /* Directory */
76 # define S_IFCHR _S_IFCHR /* Character device */
78 #if !defined(S_IFFIFO)
79 # define S_IFFIFO _S_IFFIFO /* Pipe */
82 # define S_IFREG _S_IFREG /* Regular file */
85 # define S_IREAD _S_IREAD /* Read permission */
87 #if !defined(S_IWRITE)
88 # define S_IWRITE _S_IWRITE /* Write permission */
91 # define S_IEXEC _S_IEXEC /* Execute permission */
94 # define S_IFIFO _S_IFIFO /* Pipe */
97 # define S_IFBLK 0 /* Block device */
100 # define S_IFLNK 0 /* Link */
102 #if !defined(S_IFSOCK)
103 # define S_IFSOCK 0 /* Socket */
106 #if defined(_MSC_VER)
107 # define S_IRUSR S_IREAD /* Read user */
108 # define S_IWUSR S_IWRITE /* Write user */
109 # define S_IXUSR 0 /* Execute user */
110 # define S_IRGRP 0 /* Read group */
111 # define S_IWGRP 0 /* Write group */
112 # define S_IXGRP 0 /* Execute group */
113 # define S_IROTH 0 /* Read others */
114 # define S_IWOTH 0 /* Write others */
115 # define S_IXOTH 0 /* Execute others */
118 /* Maximum length of file name */
119 #if !defined(PATH_MAX)
120 # define PATH_MAX MAX_PATH
122 #if !defined(FILENAME_MAX)
123 # define FILENAME_MAX MAX_PATH
125 #if !defined(NAME_MAX)
126 # define NAME_MAX FILENAME_MAX
129 /* File type flags for d_type */
131 #define DT_REG S_IFREG
132 #define DT_DIR S_IFDIR
133 #define DT_FIFO S_IFIFO
134 #define DT_SOCK S_IFSOCK
135 #define DT_CHR S_IFCHR
136 #define DT_BLK S_IFBLK
137 #define DT_LNK S_IFLNK
139 /* Macros for converting between st_mode and d_type */
140 #define IFTODT(mode) ((mode) & S_IFMT)
141 #define DTTOIF(type) (type)
144 * File type macros. Note that block devices, sockets and links cannot be
145 * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are
146 * only defined for compatibility. These macros should always return false
149 #define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
150 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
151 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
152 #define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
153 #define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
154 #define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR)
155 #define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
157 /* Return the exact length of d_namlen without zero terminator */
158 #define _D_EXACT_NAMLEN(p) ((p)->d_namlen)
160 /* Return number of bytes needed to store d_namlen */
161 #define _D_ALLOC_NAMLEN(p) (PATH_MAX)
169 /* Wide-character version */
171 long d_ino; /* Always zero */
172 unsigned short d_reclen; /* Structure size */
173 size_t d_namlen; /* Length of name without \0 */
174 int d_type; /* File type */
175 wchar_t d_name[PATH_MAX]; /* File name */
177 typedef struct _wdirent _wdirent;
180 struct _wdirent ent; /* Current directory entry */
181 WIN32_FIND_DATAW data; /* Private file data */
182 int cached; /* True if data is valid */
183 HANDLE handle; /* Win32 search handle */
184 wchar_t *patt; /* Initial directory name */
186 typedef struct _WDIR _WDIR;
188 static _WDIR *_wopendir (const wchar_t *dirname);
189 static struct _wdirent *_wreaddir (_WDIR *dirp);
190 static int _wclosedir (_WDIR *dirp);
191 static void _wrewinddir (_WDIR* dirp);
194 /* For compatibility with Symbian */
195 #define wdirent _wdirent
197 #define wopendir _wopendir
198 #define wreaddir _wreaddir
199 #define wclosedir _wclosedir
200 #define wrewinddir _wrewinddir
203 /* Multi-byte character versions */
205 long d_ino; /* Always zero */
206 unsigned short d_reclen; /* Structure size */
207 size_t d_namlen; /* Length of name without \0 */
208 int d_type; /* File type */
209 char d_name[PATH_MAX]; /* File name */
211 typedef struct dirent dirent;
217 typedef struct DIR DIR;
219 static DIR *opendir (const char *dirname);
220 static struct dirent *readdir (DIR *dirp);
221 static int closedir (DIR *dirp);
222 static void rewinddir (DIR* dirp);
225 /* Internal utility functions */
226 static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp);
227 static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp);
229 static int dirent_mbstowcs_s(
230 size_t *pReturnValue,
236 static int dirent_wcstombs_s(
237 size_t *pReturnValue,
240 const wchar_t *wcstr,
243 static void dirent_set_errno (int error);
246 * Open directory stream DIRNAME for read and return a pointer to the
247 * internal working area that is used to retrieve individual directory
252 const wchar_t *dirname)
257 /* Must have directory name */
258 if (dirname == NULL || dirname[0] == '\0') {
259 dirent_set_errno (ENOENT);
263 /* Allocate new _WDIR structure */
264 dirp = (_WDIR*) malloc (sizeof (struct _WDIR));
268 /* Reset _WDIR structure */
269 dirp->handle = INVALID_HANDLE_VALUE;
273 /* Compute the length of full path plus zero terminator */
274 n = GetFullPathNameW (dirname, 0, NULL, NULL);
276 /* Allocate room for absolute directory name and search pattern */
277 dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16);
281 * Convert relative directory name to an absolute one. This
282 * allows rewinddir() to function correctly even when current
283 * working directory is changed between opendir() and rewinddir().
285 n = GetFullPathNameW (dirname, n, dirp->patt, NULL);
289 /* Append search pattern \* to the directory name */
291 if (dirp->patt < p) {
296 /* Directory ends in path separator, e.g. c:\temp\ */
301 /* Directory name doesn't end in path separator */
308 /* Open directory stream and retrieve the first entry */
309 if (dirent_first (dirp)) {
310 /* Directory stream opened successfully */
313 /* Cannot retrieve first entry */
315 dirent_set_errno (ENOENT);
319 /* Cannot retrieve full path name */
320 dirent_set_errno (ENOENT);
325 /* Cannot allocate memory for search pattern */
330 /* Cannot allocate _WDIR structure */
334 /* Clean up in case of error */
344 * Read next directory entry. The directory entry is returned in dirent
345 * structure in the d_name field. Individual directory entries returned by
346 * this function include regular files, sub-directories, pseudo-directories
347 * "." and ".." as well as volume labels, hidden files and system files.
349 static struct _wdirent*
353 WIN32_FIND_DATAW *datap;
354 struct _wdirent *entp;
356 /* Read next directory entry */
357 datap = dirent_next (dirp);
362 /* Pointer to directory entry to return */
366 * Copy file name as wide-character string. If the file name is too
367 * long to fit in to the destination buffer, then truncate file name
368 * to PATH_MAX characters and zero-terminate the buffer.
371 while (n + 1 < PATH_MAX && datap->cFileName[n] != 0) {
372 entp->d_name[n] = datap->cFileName[n];
375 dirp->ent.d_name[n] = 0;
377 /* Length of file name excluding zero terminator */
381 attr = datap->dwFileAttributes;
382 if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
383 entp->d_type = DT_CHR;
384 } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
385 entp->d_type = DT_DIR;
387 entp->d_type = DT_REG;
390 /* Reset dummy fields */
392 entp->d_reclen = sizeof (struct _wdirent);
396 /* Last directory entry read */
405 * Close directory stream opened by opendir() function. This invalidates the
406 * DIR structure as well as any directory entry read previously by
416 /* Release search handle */
417 if (dirp->handle != INVALID_HANDLE_VALUE) {
418 FindClose (dirp->handle);
419 dirp->handle = INVALID_HANDLE_VALUE;
422 /* Release search pattern */
428 /* Release directory structure */
433 /* Invalid directory stream */
434 dirent_set_errno (EBADF);
441 * Rewind directory stream such that _wreaddir() returns the very first
449 /* Release existing search handle */
450 if (dirp->handle != INVALID_HANDLE_VALUE) {
451 FindClose (dirp->handle);
454 /* Open new search handle */
459 /* Get first directory entry (internal) */
460 static WIN32_FIND_DATAW*
464 WIN32_FIND_DATAW *datap;
466 /* Open directory and retrieve the first entry */
467 dirp->handle = FindFirstFileW (dirp->patt, &dirp->data);
468 if (dirp->handle != INVALID_HANDLE_VALUE) {
470 /* a directory entry is now waiting in memory */
476 /* Failed to re-open directory: no directory entry in memory */
484 /* Get next directory entry (internal) */
485 static WIN32_FIND_DATAW*
491 /* Get next directory entry */
492 if (dirp->cached != 0) {
494 /* A valid directory entry already in memory */
498 } else if (dirp->handle != INVALID_HANDLE_VALUE) {
500 /* Get the next directory entry from stream */
501 if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) {
505 /* The very last entry has been processed or an error occured */
506 FindClose (dirp->handle);
507 dirp->handle = INVALID_HANDLE_VALUE;
513 /* End of directory stream reached */
522 * Open directory stream using plain old C-string.
531 /* Must have directory name */
532 if (dirname == NULL || dirname[0] == '\0') {
533 dirent_set_errno (ENOENT);
537 /* Allocate memory for DIR structure */
538 dirp = (DIR*) malloc (sizeof (struct DIR));
540 wchar_t wname[PATH_MAX];
543 /* Convert directory name to wide-character string */
544 error = dirent_mbstowcs_s (&n, wname, PATH_MAX, dirname, PATH_MAX);
547 /* Open directory stream using wide-character name */
548 dirp->wdirp = _wopendir (wname);
550 /* Directory stream opened */
553 /* Failed to open directory stream */
559 * Cannot convert file name to wide-character string. This
560 * occurs if the string contains invalid multi-byte sequences or
561 * the output buffer is too small to contain the resulting
568 /* Cannot allocate DIR structure */
572 /* Clean up in case of error */
582 * Read next directory entry.
584 * When working with text consoles, please note that file names returned by
585 * readdir() are represented in the default ANSI code page while any output to
586 * console is typically formatted on another code page. Thus, non-ASCII
587 * characters in file names will not usually display correctly on console. The
588 * problem can be fixed in two ways: (1) change the character set of console
589 * to 1252 using chcp utility and use Lucida Console font, or (2) use
590 * _cprintf function when writing to console. The _cprinf() will re-encode
591 * ANSI strings to the console code page so many non-ASCII characters will
594 static struct dirent*
598 WIN32_FIND_DATAW *datap;
601 /* Read next directory entry */
602 datap = dirent_next (dirp->wdirp);
607 /* Attempt to convert file name to multi-byte string */
608 error = dirent_wcstombs_s(
609 &n, dirp->ent.d_name, PATH_MAX, datap->cFileName, PATH_MAX);
612 * If the file name cannot be represented by a multi-byte string,
613 * then attempt to use old 8+3 file name. This allows traditional
614 * Unix-code to access some file names despite of unicode
615 * characters, although file names may seem unfamiliar to the user.
617 * Be ware that the code below cannot come up with a short file
618 * name unless the file system provides one. At least
619 * VirtualBox shared folders fail to do this.
621 if (error && datap->cAlternateFileName[0] != '\0') {
622 error = dirent_wcstombs_s(
623 &n, dirp->ent.d_name, PATH_MAX,
624 datap->cAlternateFileName, PATH_MAX);
630 /* Initialize directory entry for return */
633 /* Length of file name excluding zero terminator */
634 entp->d_namlen = n - 1;
636 /* File attributes */
637 attr = datap->dwFileAttributes;
638 if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
639 entp->d_type = DT_CHR;
640 } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
641 entp->d_type = DT_DIR;
643 entp->d_type = DT_REG;
646 /* Reset dummy fields */
648 entp->d_reclen = sizeof (struct dirent);
652 * Cannot convert file name to multi-byte string so construct
653 * an errornous directory entry and return that. Note that
654 * we cannot return NULL as that would stop the processing
655 * of directory entries completely.
658 entp->d_name[0] = '?';
659 entp->d_name[1] = '\0';
661 entp->d_type = DT_UNKNOWN;
667 /* No more directory entries */
675 * Close directory stream.
684 /* Close wide-character directory stream */
685 ok = _wclosedir (dirp->wdirp);
688 /* Release multi-byte character version */
693 /* Invalid directory stream */
694 dirent_set_errno (EBADF);
702 * Rewind directory stream to beginning.
708 /* Rewind wide-character string directory stream */
709 _wrewinddir (dirp->wdirp);
712 /* Convert multi-byte string to wide character string */
715 size_t *pReturnValue,
723 #if defined(_MSC_VER) && _MSC_VER >= 1400
725 /* Microsoft Visual Studio 2005 or later */
726 error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count);
730 /* Older Visual Studio or non-Microsoft compiler */
733 /* Convert to wide-character string (or count characters) */
734 n = mbstowcs (wcstr, mbstr, sizeInWords);
735 if (!wcstr || n < count) {
737 /* Zero-terminate output buffer */
738 if (wcstr && sizeInWords) {
739 if (n >= sizeInWords) {
745 /* Length of resuting multi-byte string WITH zero terminator */
747 *pReturnValue = n + 1;
755 /* Could not convert string */
765 /* Convert wide-character string to multi-byte string */
768 size_t *pReturnValue,
770 size_t sizeInBytes, /* max size of mbstr */
771 const wchar_t *wcstr,
776 #if defined(_MSC_VER) && _MSC_VER >= 1400
778 /* Microsoft Visual Studio 2005 or later */
779 error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count);
783 /* Older Visual Studio or non-Microsoft compiler */
786 /* Convert to multi-byte string (or count the number of bytes needed) */
787 n = wcstombs (mbstr, wcstr, sizeInBytes);
788 if (!mbstr || n < count) {
790 /* Zero-terminate output buffer */
791 if (mbstr && sizeInBytes) {
792 if (n >= sizeInBytes) {
798 /* Lenght of resulting multi-bytes string WITH zero-terminator */
800 *pReturnValue = n + 1;
808 /* Cannot convert string */
818 /* Set errno variable */
823 #if defined(_MSC_VER) && _MSC_VER >= 1400
825 /* Microsoft Visual Studio 2005 and later */
830 /* Non-Microsoft compiler or older Microsoft compiler */
841 // florez-l: use the standard linux header
842 #else // defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ )
844 #endif // defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ )
846 #endif /*__cpPlugins__dirent__h__*/