Last active
December 11, 2018 19:25
-
-
Save algal/df5a4d5c4049276d341aa58bb2de2e25 to your computer and use it in GitHub Desktop.
Read lines in Swift
This file contains 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
// known good: Swift 4.2 | |
import Foundation | |
/// Returns an iterator that iterates through the lines of the file at path. | |
/// | |
/// - Parameter path: path of the file to read | |
/// - Returns: the iterator, or nil if the file could not be read | |
func lineSequence(forFileAtPath path:String) -> AnyIterator<String>? | |
{ | |
guard let handle = FileHandle.init(forReadingAtPath: path) else { return nil } | |
let filePtr = fdopen(handle.fileDescriptor, | |
"r".cString(using: String.Encoding.ascii)!) | |
return AnyIterator({ () -> String? in | |
var line:UnsafeMutablePointer<Int8>? = nil | |
var linecap:Int = 0 | |
defer { free(line) } | |
if getline(&line, &linecap, filePtr) > 0, | |
let cStringLine = UnsafePointer<CChar>(line) | |
{ | |
return String(cString: cStringLine) | |
} | |
else { | |
return nil | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment