[swift-users] file io in Swift 2.2 for Linux (would like to be pointed in the right direction)
Quinn "The Eskimo!"
eskimo1 at apple.com
Mon May 23 03:24:09 CDT 2016
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
More information about the swift-users
mailing list