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__ )
35 * Define architecture flags so we don't need to include windows.h.
36 * Avoiding windows.h makes it simpler to use windows sockets in conjunction
39 #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_IX86)
42 #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_AMD64)
54 #include <sys/types.h>
58 /* Indicates that d_type field is available in dirent structure */
59 #define ___CPPLUGINS_DIRENT___H__AVE_D_TYPE
61 /* Indicates that d_namlen field is available in dirent structure */
62 #define ___CPPLUGINS_DIRENT___H__AVE_D_NAMLEN
64 /* Entries missing from MSVC 6.0 */
65 #if !defined(FILE_ATTRIBUTE_DEVICE)
66 # define FILE_ATTRIBUTE_DEVICE 0x40
69 /* File type and permission flags for stat() */
71 # define S_IFMT _S_IFMT /* File type mask */
74 # define S_IFDIR _S_IFDIR /* Directory */
77 # define S_IFCHR _S_IFCHR /* Character device */
79 #if !defined(S_IFFIFO)
80 # define S_IFFIFO _S_IFFIFO /* Pipe */
83 # define S_IFREG _S_IFREG /* Regular file */
86 # define S_IREAD _S_IREAD /* Read permission */
88 #if !defined(S_IWRITE)
89 # define S_IWRITE _S_IWRITE /* Write permission */
92 # define S_IEXEC _S_IEXEC /* Execute permission */
95 # define S_IFIFO _S_IFIFO /* Pipe */
98 # define S_IFBLK 0 /* Block device */
100 #if !defined(S_IFLNK)
101 # define S_IFLNK 0 /* Link */
103 #if !defined(S_IFSOCK)
104 # define S_IFSOCK 0 /* Socket */
107 #if defined(_MSC_VER)
108 # define S_IRUSR S_IREAD /* Read user */
109 # define S_IWUSR S_IWRITE /* Write user */
110 # define S_IXUSR 0 /* Execute user */
111 # define S_IRGRP 0 /* Read group */
112 # define S_IWGRP 0 /* Write group */
113 # define S_IXGRP 0 /* Execute group */
114 # define S_IROTH 0 /* Read others */
115 # define S_IWOTH 0 /* Write others */
116 # define S_IXOTH 0 /* Execute others */
119 /* Maximum length of file name */
120 #if !defined(PATH_MAX)
121 # define PATH_MAX MAX_PATH
123 #if !defined(FILENAME_MAX)
124 # define FILENAME_MAX MAX_PATH
126 #if !defined(NAME_MAX)
127 # define NAME_MAX FILENAME_MAX
130 /* File type flags for d_type */
132 #define DT_REG S_IFREG
133 #define DT_DIR S_IFDIR
134 #define DT_FIFO S_IFIFO
135 #define DT_SOCK S_IFSOCK
136 #define DT_CHR S_IFCHR
137 #define DT_BLK S_IFBLK
138 #define DT_LNK S_IFLNK
140 /* Macros for converting between st_mode and d_type */
141 #define IFTODT(mode) ((mode) & S_IFMT)
142 #define DTTOIF(type) (type)
145 * File type macros. Note that block devices, sockets and links cannot be
146 * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are
147 * only defined for compatibility. These macros should always return false
150 #define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
151 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
152 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
153 #define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
154 #define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
155 #define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR)
156 #define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
158 /* Return the exact length of d_namlen without zero terminator */
159 #define _D_EXACT_NAMLEN(p) ((p)->d_namlen)
161 /* Return number of bytes needed to store d_namlen */
162 #define _D_ALLOC_NAMLEN(p) (PATH_MAX)
170 /* Wide-character version */
172 long d_ino; /* Always zero */
173 unsigned short d_reclen; /* Structure size */
174 size_t d_namlen; /* Length of name without \0 */
175 int d_type; /* File type */
176 wchar_t d_name[PATH_MAX]; /* File name */
178 typedef struct _wdirent _wdirent;
181 struct _wdirent ent; /* Current directory entry */
182 WIN32_FIND_DATAW data; /* Private file data */
183 int cached; /* True if data is valid */
184 HANDLE handle; /* Win32 search handle */
185 wchar_t *patt; /* Initial directory name */
187 typedef struct _WDIR _WDIR;
189 static _WDIR *_wopendir (const wchar_t *dirname);
190 static struct _wdirent *_wreaddir (_WDIR *dirp);
191 static int _wclosedir (_WDIR *dirp);
192 static void _wrewinddir (_WDIR* dirp);
195 /* For compatibility with Symbian */
196 #define wdirent _wdirent
198 #define wopendir _wopendir
199 #define wreaddir _wreaddir
200 #define wclosedir _wclosedir
201 #define wrewinddir _wrewinddir
204 /* Multi-byte character versions */
206 long d_ino; /* Always zero */
207 unsigned short d_reclen; /* Structure size */
208 size_t d_namlen; /* Length of name without \0 */
209 int d_type; /* File type */
210 char d_name[PATH_MAX]; /* File name */
212 typedef struct dirent dirent;
218 typedef struct DIR DIR;
220 static DIR *opendir (const char *dirname);
221 static struct dirent *readdir (DIR *dirp);
222 static int closedir (DIR *dirp);
223 static void rewinddir (DIR* dirp);
226 /* Internal utility functions */
227 static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp);
228 static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp);
230 static int dirent_mbstowcs_s(
231 size_t *pReturnValue,
237 static int dirent_wcstombs_s(
238 size_t *pReturnValue,
241 const wchar_t *wcstr,
244 static void dirent_set_errno (int error);
247 * Open directory stream DIRNAME for read and return a pointer to the
248 * internal working area that is used to retrieve individual directory
253 const wchar_t *dirname)
258 /* Must have directory name */
259 if (dirname == NULL || dirname[0] == '\0') {
260 dirent_set_errno (ENOENT);
264 /* Allocate new _WDIR structure */
265 dirp = (_WDIR*) malloc (sizeof (struct _WDIR));
269 /* Reset _WDIR structure */
270 dirp->handle = INVALID_HANDLE_VALUE;
274 /* Compute the length of full path plus zero terminator */
275 n = GetFullPathNameW (dirname, 0, NULL, NULL);
277 /* Allocate room for absolute directory name and search pattern */
278 dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16);
282 * Convert relative directory name to an absolute one. This
283 * allows rewinddir() to function correctly even when current
284 * working directory is changed between opendir() and rewinddir().
286 n = GetFullPathNameW (dirname, n, dirp->patt, NULL);
290 /* Append search pattern \* to the directory name */
292 if (dirp->patt < p) {
297 /* Directory ends in path separator, e.g. c:\temp\ */
302 /* Directory name doesn't end in path separator */
309 /* Open directory stream and retrieve the first entry */
310 if (dirent_first (dirp)) {
311 /* Directory stream opened successfully */
314 /* Cannot retrieve first entry */
316 dirent_set_errno (ENOENT);
320 /* Cannot retrieve full path name */
321 dirent_set_errno (ENOENT);
326 /* Cannot allocate memory for search pattern */
331 /* Cannot allocate _WDIR structure */
335 /* Clean up in case of error */
345 * Read next directory entry. The directory entry is returned in dirent
346 * structure in the d_name field. Individual directory entries returned by
347 * this function include regular files, sub-directories, pseudo-directories
348 * "." and ".." as well as volume labels, hidden files and system files.
350 static struct _wdirent*
354 WIN32_FIND_DATAW *datap;
355 struct _wdirent *entp;
357 /* Read next directory entry */
358 datap = dirent_next (dirp);
363 /* Pointer to directory entry to return */
367 * Copy file name as wide-character string. If the file name is too
368 * long to fit in to the destination buffer, then truncate file name
369 * to PATH_MAX characters and zero-terminate the buffer.
372 while (n + 1 < PATH_MAX && datap->cFileName[n] != 0) {
373 entp->d_name[n] = datap->cFileName[n];
376 dirp->ent.d_name[n] = 0;
378 /* Length of file name excluding zero terminator */
382 attr = datap->dwFileAttributes;
383 if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
384 entp->d_type = DT_CHR;
385 } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
386 entp->d_type = DT_DIR;
388 entp->d_type = DT_REG;
391 /* Reset dummy fields */
393 entp->d_reclen = sizeof (struct _wdirent);
397 /* Last directory entry read */
406 * Close directory stream opened by opendir() function. This invalidates the
407 * DIR structure as well as any directory entry read previously by
417 /* Release search handle */
418 if (dirp->handle != INVALID_HANDLE_VALUE) {
419 FindClose (dirp->handle);
420 dirp->handle = INVALID_HANDLE_VALUE;
423 /* Release search pattern */
429 /* Release directory structure */
434 /* Invalid directory stream */
435 dirent_set_errno (EBADF);
442 * Rewind directory stream such that _wreaddir() returns the very first
450 /* Release existing search handle */
451 if (dirp->handle != INVALID_HANDLE_VALUE) {
452 FindClose (dirp->handle);
455 /* Open new search handle */
460 /* Get first directory entry (internal) */
461 static WIN32_FIND_DATAW*
465 WIN32_FIND_DATAW *datap;
467 /* Open directory and retrieve the first entry */
468 dirp->handle = FindFirstFileW (dirp->patt, &dirp->data);
469 if (dirp->handle != INVALID_HANDLE_VALUE) {
471 /* a directory entry is now waiting in memory */
477 /* Failed to re-open directory: no directory entry in memory */
485 /* Get next directory entry (internal) */
486 static WIN32_FIND_DATAW*
492 /* Get next directory entry */
493 if (dirp->cached != 0) {
495 /* A valid directory entry already in memory */
499 } else if (dirp->handle != INVALID_HANDLE_VALUE) {
501 /* Get the next directory entry from stream */
502 if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) {
506 /* The very last entry has been processed or an error occured */
507 FindClose (dirp->handle);
508 dirp->handle = INVALID_HANDLE_VALUE;
514 /* End of directory stream reached */
523 * Open directory stream using plain old C-string.
532 /* Must have directory name */
533 if (dirname == NULL || dirname[0] == '\0') {
534 dirent_set_errno (ENOENT);
538 /* Allocate memory for DIR structure */
539 dirp = (DIR*) malloc (sizeof (struct DIR));
541 wchar_t wname[PATH_MAX];
544 /* Convert directory name to wide-character string */
545 error = dirent_mbstowcs_s (&n, wname, PATH_MAX, dirname, PATH_MAX);
548 /* Open directory stream using wide-character name */
549 dirp->wdirp = _wopendir (wname);
551 /* Directory stream opened */
554 /* Failed to open directory stream */
560 * Cannot convert file name to wide-character string. This
561 * occurs if the string contains invalid multi-byte sequences or
562 * the output buffer is too small to contain the resulting
569 /* Cannot allocate DIR structure */
573 /* Clean up in case of error */
583 * Read next directory entry.
585 * When working with text consoles, please note that file names returned by
586 * readdir() are represented in the default ANSI code page while any output to
587 * console is typically formatted on another code page. Thus, non-ASCII
588 * characters in file names will not usually display correctly on console. The
589 * problem can be fixed in two ways: (1) change the character set of console
590 * to 1252 using chcp utility and use Lucida Console font, or (2) use
591 * _cprintf function when writing to console. The _cprinf() will re-encode
592 * ANSI strings to the console code page so many non-ASCII characters will
595 static struct dirent*
599 WIN32_FIND_DATAW *datap;
602 /* Read next directory entry */
603 datap = dirent_next (dirp->wdirp);
608 /* Attempt to convert file name to multi-byte string */
609 error = dirent_wcstombs_s(
610 &n, dirp->ent.d_name, PATH_MAX, datap->cFileName, PATH_MAX);
613 * If the file name cannot be represented by a multi-byte string,
614 * then attempt to use old 8+3 file name. This allows traditional
615 * Unix-code to access some file names despite of unicode
616 * characters, although file names may seem unfamiliar to the user.
618 * Be ware that the code below cannot come up with a short file
619 * name unless the file system provides one. At least
620 * VirtualBox shared folders fail to do this.
622 if (error && datap->cAlternateFileName[0] != '\0') {
623 error = dirent_wcstombs_s(
624 &n, dirp->ent.d_name, PATH_MAX,
625 datap->cAlternateFileName, PATH_MAX);
631 /* Initialize directory entry for return */
634 /* Length of file name excluding zero terminator */
635 entp->d_namlen = n - 1;
637 /* File attributes */
638 attr = datap->dwFileAttributes;
639 if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
640 entp->d_type = DT_CHR;
641 } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
642 entp->d_type = DT_DIR;
644 entp->d_type = DT_REG;
647 /* Reset dummy fields */
649 entp->d_reclen = sizeof (struct dirent);
653 * Cannot convert file name to multi-byte string so construct
654 * an errornous directory entry and return that. Note that
655 * we cannot return NULL as that would stop the processing
656 * of directory entries completely.
659 entp->d_name[0] = '?';
660 entp->d_name[1] = '\0';
662 entp->d_type = DT_UNKNOWN;
668 /* No more directory entries */
676 * Close directory stream.
685 /* Close wide-character directory stream */
686 ok = _wclosedir (dirp->wdirp);
689 /* Release multi-byte character version */
694 /* Invalid directory stream */
695 dirent_set_errno (EBADF);
703 * Rewind directory stream to beginning.
709 /* Rewind wide-character string directory stream */
710 _wrewinddir (dirp->wdirp);
713 /* Convert multi-byte string to wide character string */
716 size_t *pReturnValue,
724 #if defined(_MSC_VER) && _MSC_VER >= 1400
726 /* Microsoft Visual Studio 2005 or later */
727 error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count);
731 /* Older Visual Studio or non-Microsoft compiler */
734 /* Convert to wide-character string (or count characters) */
735 n = mbstowcs (wcstr, mbstr, sizeInWords);
736 if (!wcstr || n < count) {
738 /* Zero-terminate output buffer */
739 if (wcstr && sizeInWords) {
740 if (n >= sizeInWords) {
746 /* Length of resuting multi-byte string WITH zero terminator */
748 *pReturnValue = n + 1;
756 /* Could not convert string */
766 /* Convert wide-character string to multi-byte string */
769 size_t *pReturnValue,
771 size_t sizeInBytes, /* max size of mbstr */
772 const wchar_t *wcstr,
777 #if defined(_MSC_VER) && _MSC_VER >= 1400
779 /* Microsoft Visual Studio 2005 or later */
780 error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count);
784 /* Older Visual Studio or non-Microsoft compiler */
787 /* Convert to multi-byte string (or count the number of bytes needed) */
788 n = wcstombs (mbstr, wcstr, sizeInBytes);
789 if (!mbstr || n < count) {
791 /* Zero-terminate output buffer */
792 if (mbstr && sizeInBytes) {
793 if (n >= sizeInBytes) {
799 /* Lenght of resulting multi-bytes string WITH zero-terminator */
801 *pReturnValue = n + 1;
809 /* Cannot convert string */
819 /* Set errno variable */
824 #if defined(_MSC_VER) && _MSC_VER >= 1400
826 /* Microsoft Visual Studio 2005 and later */
831 /* Non-Microsoft compiler or older Microsoft compiler */
842 // florez-l: use the standard linux header
843 #else // defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ )
845 #endif // defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ )
847 #endif /*__CPPLUGINS_DIRENT___H__*/