Last active
November 29, 2023 12:32
-
-
Save kristopherjohnson/4bafee0b489add42a61f to your computer and use it in GitHub Desktop.
Example of using opendir/readdir/closedir with Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| // Get current working directory | |
| var wdbuf: [Int8] = Array(count: Int(MAXNAMLEN), repeatedValue: 0) | |
| let workingDirectory = getcwd(&wdbuf, UInt(MAXNAMLEN)) | |
| // Open the directory | |
| let dir = opendir(workingDirectory) | |
| if dir != nil { | |
| // Use readdir to get each element | |
| var dirent = readdir(dir) | |
| while dirent != nil { | |
| var name: [CChar] = Array() | |
| // dirent.d_name is defined as a tuple with | |
| // MAXNAMLEN elements. The only way to | |
| // iterate over those elements is via | |
| // reflection | |
| // | |
| // Credit: dankogi at http://stackoverflow.com/questions/24299045/any-way-to-iterate-a-tuple-in-swift | |
| let d_namlen = dirent.memory.d_namlen | |
| let d_name = dirent.memory.d_name | |
| let mirror = reflect(d_name) | |
| for i in 0..<d_namlen { | |
| let (s, m) = mirror[Int(i)] | |
| name.append(m.value as Int8) | |
| } | |
| // null-terminate it and convert to a string | |
| name.append(0) | |
| if let s = String.fromCString(name) { | |
| println(s) | |
| } | |
| dirent = readdir(dir) | |
| } | |
| closedir(dir) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a similar version of this code adopted to Swift 5.9. It excludes ".", ".." and similar files because I find them useless. Also it returns
[URL]instead of[String].