Last active
August 26, 2024 18:54
-
-
Save AlexandrGraschenkov/1167ec4517331f1070e9f45ae9b5b16c to your computer and use it in GitHub Desktop.
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
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