Skip to content

Instantly share code, notes, and snippets.

@cham-s
Forked from algal/SwiftLineReader.swift
Last active August 4, 2017 19:12
Show Gist options
  • Save cham-s/2eca42ee5dfb447e0c12788d306e9648 to your computer and use it in GitHub Desktop.
Save cham-s/2eca42ee5dfb447e0c12788d306e9648 to your computer and use it in GitHub Desktop.
Read a file one line at a time in Swift
/**
Original snipet from: https://gist.github.com/algal/23b10062a558aec7679e4c854096f88e
Forked to play around and learn sequence.
*/
import Darwin
struct LineIterator: IteratorProtocol {
var file: UnsafeMutablePointer<FILE>
init (file: UnsafeMutablePointer<FILE>) {
self.file = file
}
mutating func next() -> String? {
var line: UnsafeMutablePointer<CChar>?
var linecap: Int = 0
defer { free(line) }
return getline(&line, &linecap, file) > 0 ? String(cString: line!) : nil
}
}
struct LineSequence: Sequence {
let file: UnsafeMutablePointer<FILE>
func makeIterator() -> LineIterator {
return LineIterator(file: file)
}
}
let path = "path/to/file"
let file = fopen(path, "r")
if let filePointer = file {
let lineSequence = LineSequence(file: filePointer)
for line in lineSequence {
print(line, separator: "", terminator: "")
}
} else {
print("Path not valid.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment