// Copyright © 2017 andrewwoz

import Foundation

/// Read text file line by line in efficient way
public class LineReader {
    public let path: String
    
    fileprivate let file: UnsafeMutablePointer<FILE>!
    
    init?(path: String) {
        self.path = path
        file = fopen(path, "r")
        guard file != nil else { return nil }
    }
    
    public var nextLine: String? {
        var line:UnsafeMutablePointer<CChar>? = nil
        var linecap:Int = 0
        defer { if (line != nil) { free(line!) } }
        return getline(&line, &linecap, file) > 0 ? String(cString: line!) : nil
    }
    
    deinit {
        fclose(file)
    }
}

extension LineReader: Sequence {
    public func  makeIterator() -> AnyIterator<String> {
        return AnyIterator<String> {
            return self.nextLine
        }
    }
}

// Copyright © 2017 andrewwoz

import Foundation

/// Read text file line by line in efficient way
public class LineReader {
    public let path: String
    
    fileprivate let file: UnsafeMutablePointer<FILE>!
    
    init?(path: String) {
        self.path = path
        file = fopen(path, "r")
        guard file != nil else { return nil }
    }
    
    public var nextLine: String? {
        var line:UnsafeMutablePointer<CChar>? = nil
        var linecap:Int = 0
        defer { free(line) }
        return getline(&line, &linecap, file) > 0 ? String(cString: line!) : nil
    }
    
    deinit {
        fclose(file)
    }
}

extension LineReader: Sequence {
    public func  makeIterator() -> AnyIterator<String> {
        return AnyIterator<String> {
            return self.nextLine
        }
    }
}

--- 
+++ 
@@ -17,7 +17,7 @@
     public var nextLine: String? {
         var line:UnsafeMutablePointer<CChar>? = nil
         var linecap:Int = 0
-        defer { free(line) }
+        defer { if (line != nil) { free(line!) } }
         return getline(&line, &linecap, file) > 0 ? String(cString: line!) : nil
     }
     
Fix compilation on Xcode 13

On Xcode 13, an error is reported:
```
LineReader.swift:20:22: value of optional type 'UnsafeMutablePointer<CChar>?' (aka 'Optional<UnsafeMutablePointer<Int8>>') must be unwrapped to a value of type 'UnsafeMutablePointer<CChar>' (aka 'UnsafeMutablePointer<Int8>')
```
