Last active
October 6, 2016 02:01
-
-
Save erica/b3abc87b0baa0e60b3c8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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