Skip to content

Instantly share code, notes, and snippets.

@algal
Last active December 11, 2018 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save algal/df5a4d5c4049276d341aa58bb2de2e25 to your computer and use it in GitHub Desktop.
Save algal/df5a4d5c4049276d341aa58bb2de2e25 to your computer and use it in GitHub Desktop.
Read lines in Swift
// 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