Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
public struct StderrOutputStream: OutputStreamType {
// Support for file redirection back to console
private static var fpos : fpos_t = 0
private static var fd = dup(fileno(stderr))
private static var isRedirected_ = false
public static var isRedirected : Bool {return isRedirected_}
// When false, the output file is rewritten and not appended
private static var appendToFile = true
// When true, output is echoed to stdout
public static var echo = false
// When non-nil, output is redirected to the specified file path
public static func redirectOutputToPath(path: String?) {
if let path = path {
if !isRedirected {
// Set up if this is new redirection
var pos = UnsafeMutablePointer<fpos_t>.alloc(1)
fgetpos(stderr, pos)
fpos = pos.memory
fd = dup(fileno(stderr))
if appendToFile {
freopen(path, "a", stderr)
} else {
freopen(path, "w", stderr)
isRedirected_ = true
} else {
if !isRedirected {
// do not respond if not redirected
dup2(fd, fileno(stderr))
fsetpos(stderr, &fpos)
isRedirected_ = false
public static let stream = StderrOutputStream()
public func write(string: String) {
fputs(string, stderr)
if StderrOutputStream.echo && StderrOutputStream.isRedirected {fputs(string, stdout)}
public var errStream =
func swlog(format : String, args : CVarArgType...) {
println(String(format: format, arguments: args), &errStream)

This comment has been minimized.

Copy link

@danielphillips danielphillips commented May 23, 2015

What's with the underscore suffix in your private member - private static var isRedirected_ = false
Is this just a preference vs a prefixed underscore or is this preferred in Swift?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.