nvzqz / FileKit

Simple and expressive file management in Swift
https://nvzqz.github.io/FileKit/docs/
MIT License
2.34k stars 207 forks source link

How to read and write line by line? #40

Closed rpural closed 7 years ago

rpural commented 7 years ago

Why is it that there are no file read and write routines to read individual lines from a file, or write individual lines to a file, without having to open and close the file around each line (such as your |>> operator)?

I really love the Swift language, except that I can't read or write a text file in a normal manner. Reading the whole file at once is great... unless your file is several Megabytes, or several Terabytes long. I really just want to read a file, line by line, in a way that won't eat up all of memory.

I'm just frustrated, saw your library, and thought that it might be the solution I was looking for. O.o

rpural commented 7 years ago

I think I've found what I required in your framework. Trying to code up a sample to test it now.

rpural commented 7 years ago

I was able to come up with this in the playground. I think that this is what I'm looking for, but there's no documentation for these classes in the docs displayed on the github page.

let teststream = TextFileStreamWriter(path: Path("/Users/rpn01/Documents/Shared Playground Data/fileKit_teststream"))

for i in 1...10 { teststream!.write(line: String(i)) }

teststream!.close()

let teststream2 = TextFileStreamReader(path: Path("/Users/rpn01/Documents/Shared Playground Data/fileKit_teststream"))

while let line = teststream2?.nextLine() { print(line) }

teststream2?.close()

I think this is what I've been looking for. Hopefully, you can confirm it. Thanks in advance...

nvzqz commented 7 years ago

Hi, I'm not entirely familiar with the TextFileStream API since these features were not made by me but rather @phimage. It seems that based on your example, it may work as the solution you were looking for. Currently I'm not able to test this.

Let me know if this is a suitable solution, otherwise I'll look into implementing such features.

phimage commented 7 years ago

Yes TextFileStreamReader is to read line by line , to avoid memory issues

you can also create a TestFileand do

            if let reader = textFile.streamReader() {
                defer {
                    reader.close()
                } 
                for line in reader {
                   // do something with the line
                }  
            } else {
               warn("Failed to create reader")
            }

code from test https://github.com/nvzqz/FileKit/blob/develop/Tests/FileKitTests.swift you can find also code for streamWriter

rpural commented 7 years ago

Yes, this does satisfy my largest complaint about Swift in general. How they could design a language and core libraries while overlooking such a basic and necessary feature is beyond me. Thanks for filling the gap. :)