How to make NSOutputStream redirect to standard output?
It doesn't appear there's a built-in way to do this. If you can use NSFileHandle
instead of NSOutputStream
, you can use [NSFileHandle fileHandleWithStandardOutput]
. If you have to use NSOutputStream
, try something like this:
// untested!
@interface FileHandleOutputStream : NSOutputStream
+ (FileHandleOutputStream *)outputStreamWithFileHandle:(NSFileHandle *)fileHandle;
- (id)initWithFileHandle:(NSFileHandle *)fileHandle;
@end
@implementation FileHandleOutputStream {
NSFileHandle *_fileHandle;
}
+ (FileHandleOutputStream *)outputStreamWithFileHandle:(NSFileHandle *)fileHandle {
return [[[self alloc] initWithFileHandle:fileHandle] autorelease];
}
- (id)initWithFileHandle:(NSFileHandle *)fileHandle {
if (self = [super init]) {
_fileHandle = [fileHandle retain];
}
return self;
}
- (void)dealloc {
[_fileHandle release];
[super dealloc];
}
- (BOOL)hasSpaceAvailable {
return YES;
}
- (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)length {
[_fileHandle writeData:[NSData dataWithBytesNoCopy:buffer
length:length
freeWhenDone:NO]];
return length;
}
Now use
FileHandleOutputStream *myStrem = [FileHandleOutputStream outputStreamWithFileHandle:
[NSFileHandle fileHandleWithStandardOutput]];