[swift-users] file io in Swift 2.2 for Linux (would like to be pointed in the right direction)

Matthias Zenger matthias at objecthub.net
Sat Jun 4 20:25:50 CDT 2016

Quinn, thanks for the example. I agree that Foundation makes it easier by
loading the data fully into memory. I still don't understand if it's
currently actually *possible* to use non C-based solutions in Swift which
use streaming. I wanted to use NSFileHandle (for a use case that requires
streaming) and realized that this is an API that cannot really be used in
Swift because it's based on Objective-C exceptions. Are there any


*Matthias Zenger* matthias at objecthub.net

On Mon, May 23, 2016 at 10:24 AM, Quinn "The Eskimo!" via swift-users <
swift-users at swift.org> wrote:

> On 18 May 2016, at 23:02, John Myers via swift-users <
> swift-users at swift.org> wrote:
> > I've been having trouble figuring out how to read and write data to a
> textfile, and not finding much out there for Swift on Linux.
> Sorry about being complicit in the one-shot vs streaming I/O diversion.
> It’s true that Swift’s streaming I/O story is in flux and I’m sure that
> Jens and co. will have fun designing its replacement, but right now I’d
> kinda like to bring this back to the original question.
> Below is a snippet that shows how to process a file line-by-line using
> Foundation APIs.  As you can see, if you’re just trying to runs simple
> tests on the lines in a text file, doing this with Foundation is much
> easier than doing it with the current lower-level APIs.
> ---------------------------------------------------------------------------
> import Foundation
> func quoteFile(atPath filePath: String) throws {
>     let input = try NSString(contentsOfFile: filePath, encoding:
> NSUTF8StringEncoding)
>     let inputLines = input.components(separatedBy: "\n")
>     var outputLines: [String] = []
>     for line in inputLines {
>         let newLine = "> " + line
>         outputLines.append(newLine)
>     }
>     let output = outputLines.joined(separator: "\n")
>     try output.write(toFile: filePath, atomically: true, encoding:
> NSUTF8StringEncoding)
> }
> try! quoteFile(atPath: "/Users/quinn/victim.txt")
> ---------------------------------------------------------------------------
> I tested this on OS X (don’t have Linux set up, sorry) with the
> “2016-05-09 (a)” Swift development snapshot.
> Share and Enjoy
> --
> Quinn "The Eskimo!"                    <http://www.apple.com/developer/>
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160605/b0107926/attachment.html>

More information about the swift-users mailing list