1 /** @file msvc_dirent.cc
2 * @brief Implementation of dirent functions using WIN32 API.
5 Implementation of POSIX directory browsing functions and types for Win32.
7 Author: Kevlin Henney (kevlin@acm.org, kevlin@curbralan.com)
8 History: Created March 1997. Updated June 2003.
9 Fixes since importing into Xapian:
10 2008-03-04 Fixed readdir() not to set errno to ENOENT when the
11 end of the directory is reached.
13 Copyright Kevlin Henney, 1997, 2003. All rights reserved.
15 Permission to use, copy, modify, and distribute this software and its
16 documentation for any purpose is hereby granted without fee, provided
17 that this copyright and permissions notice appear in all copies and
20 This software is supplied "as is" without express or implied warranty.
22 But that said, if there are any problems please get in touch.
28 #include "msvc_dirent.h"
30 #include <io.h> /* _findfirst and _findnext set errno iff they return -1 */
41 long handle
; /* -1 for failed rewind */
42 struct _finddata_t info
;
43 struct dirent result
; /* d_name null iff first time */
44 char *name
; /* null-terminated char string */
47 DIR *opendir(const char *name
)
53 size_t base_length
= strlen(name
);
54 const char *all
= /* search pattern must end with suitable wildcard */
55 strchr("/\\", name
[base_length
- 1]) ? "*" : "/*";
57 if((dir
= (DIR *) malloc(sizeof *dir
)) != 0 &&
58 (dir
->name
= (char *) malloc(base_length
+ strlen(all
) + 1)) != 0)
60 strcat(strcpy(dir
->name
, name
), all
);
62 if((dir
->handle
= (long) _findfirst(dir
->name
, &dir
->info
)) != -1)
64 dir
->result
.d_name
= 0;
88 int closedir(DIR *dir
)
96 result
= _findclose(dir
->handle
);
103 if(result
== -1) /* map all errors to EBADF */
111 struct dirent
*readdir(DIR *dir
)
113 struct dirent
*result
= 0;
115 if(dir
&& dir
->handle
!= -1)
117 if(!dir
->result
.d_name
) {
118 result
= &dir
->result
;
119 result
->d_name
= dir
->info
.name
;
121 int orig_errno
= errno
;
122 if (_findnext(dir
->handle
, &dir
->info
) != -1) {
123 result
= &dir
->result
;
124 result
->d_name
= dir
->info
.name
;
125 } else if (errno
== ENOENT
) {
126 // _findnext sets errno to ENOENT when the end of the directory
127 // is reached. However, according to POSIX, the value of errno
128 // should not be changed by this condition. Therefore, we have
129 // to set it back to the original value.
142 void rewinddir(DIR *dir
)
144 if(dir
&& dir
->handle
!= -1)
146 _findclose(dir
->handle
);
147 dir
->handle
= (long) _findfirst(dir
->name
, &dir
->info
);
148 dir
->result
.d_name
= 0;