Skip to content

Instantly share code, notes, and snippets.

@AlexandrGraschenkov
Last active August 26, 2024 18:54
Show Gist options
  • Save AlexandrGraschenkov/1167ec4517331f1070e9f45ae9b5b16c to your computer and use it in GitHub Desktop.
Save AlexandrGraschenkov/1167ec4517331f1070e9f45ae9b5b16c to your computer and use it in GitHub Desktop.
import Darwin
class FileLineReader {
init?(path: String, removeNewLineOnEnd: Bool = true) {
file = fopen(path, "r")
self.removeNewLineOnEnd = removeNewLineOnEnd
if file == nil {
return nil
}
}
deinit {
fclose(file)
}
var iterator: AnyIterator<String> {
return AnyIterator(self.getNextLine)
}
func getNextLine() -> String? {
var line: UnsafeMutablePointer<CChar>!
var linecap: Int = 0
defer { free(line) }
if getline(&line, &linecap, file) > 0 {
if removeNewLineOnEnd {
var i = 0
while line[i] != 0 { i += 1 }
if i > 0 && line[i-1] == 10 {
line[i-1] = 0
}
}
return String(cString: line)
} else {
return nil
}
}
private let file: UnsafeMutablePointer<FILE>!
private let removeNewLineOnEnd: Bool
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment