Skip to content

Instantly share code, notes, and snippets.

@erica
Last active October 6, 2016 02:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/b3abc87b0baa0e60b3c8 to your computer and use it in GitHub Desktop.
Save erica/b3abc87b0baa0e60b3c8 to your computer and use it in GitHub Desktop.
//
// main.swift
// Chapter2
//
// Created by Erica Sadun on 7/2/15.
// Copyright © 2015 Erica Sadun. All rights reserved.
//
import Foundation
public class OutputStream : OutputStreamType {
let stream : UnsafeMutablePointer<FILE> // Selected stream
var path : NSString? = nil // File path
// Create with stream
public init(_ stream: UnsafeMutablePointer<FILE>) {
self.stream = stream
}
// Create with output file
public init?(path : String, append : Bool = false) {
if (append) {
stream = fopen(path, "a")
} else {
stream = fopen(path, "w")
}
if stream == nil {return nil}
self.path = path
}
// stderr
public static func stderr() -> OutputStream {
return OutputStream(Darwin.stderr)
}
// stdout
public static func stdout() -> OutputStream {
return OutputStream(Darwin.stdout)
}
// Conform to OutputStreamType
public func write(string: String) {
fputs(string, stream)
}
// Clean up open FILE
deinit {
if path != nil {fclose(stream)}
}
}
public var errStream = OutputStream.stderr()
public var stdStream = OutputStream.stdout()
print("Testing error output", &errStream)
print("Hello ", &errStream, appendNewline: false)
print("World", &errStream, appendNewline: true)
print("Testing std output", &errStream)
print("Hello ", &stdStream, appendNewline: false)
print("World", &stdStream, appendNewline: true)
if var testStream = OutputStream(path: "~/Desktop/output.txt".stringByExpandingTildeInPath) {
print("Testing custom output", &testStream)
print("Hello ", &testStream, appendNewline: false)
print("World", &testStream, appendNewline: true)
print("Output sent to \(testStream.path)")
} else {
print("Failed to create custom output")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment