Skip to content

Commit 7e3ff2b

Browse files
committed
Implement file enumeration on Windows
1 parent cf74be7 commit 7e3ff2b

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

Xcode/Sources/String+File.swift

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,14 +114,33 @@ extension String {
114114
}
115115

116116
public func files() throws -> [String] {
117+
var results = [String]()
117118
#if os(Windows)
118-
fatalError("Not implemented")
119+
var data = WIN32_FIND_DATAW()
120+
let handle = self.withCString(encodedAs: UTF16.self) {
121+
return FindFirstFileW($0, &data)
122+
}
123+
guard handle != INVALID_HANDLE_VALUE else {
124+
throw FileError.error(Int32(GetLastError()))
125+
}
126+
defer { FindClose(handle) }
127+
let appendToResults = {
128+
let fileName = withUnsafePointer(to: &data.cFileName) { (ptr) -> String in
129+
ptr.withMemoryRebound(to: unichar.self, capacity: Int(MAX_PATH * 2)) {
130+
String(utf16CodeUnits: $0, count: wcslen($0))
131+
}
132+
}
133+
results.append(fileName)
134+
}
135+
appendToResults()
136+
while FindNextFileW(handle, &data) {
137+
appendToResults()
138+
}
119139
#else
120140
guard let dir = self.withCString({ opendir($0) }) else {
121141
throw FileError.error(errno)
122142
}
123143
defer { closedir(dir) }
124-
var results = [String]()
125144
while let ent = readdir(dir) {
126145
var name = ent.pointee.d_name
127146
let fileName = withUnsafePointer(to: &name) { (ptr) -> String? in
@@ -141,8 +160,8 @@ extension String {
141160
results.append(fileName)
142161
}
143162
}
144-
return results
145163
#endif
164+
return results
146165
}
147166

148167
private func withStat<T>(_ closure: ((stat?) throws -> T)) throws -> T {

0 commit comments

Comments
 (0)