-
-
Save cham-s/2eca42ee5dfb447e0c12788d306e9648 to your computer and use it in GitHub Desktop.
Read a file one line at a time 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
/** | |
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