objective-c – 如何将STDOUT重定向到NSTextView?

有人能告诉我如何将Stdout重定向到NSTextView吗?

以及NSLog打印的信息是否属于std?

谢谢

解决方法

下面的代码使用dup2将stdout插入NSPipe对象的写端.使用GCD调度源观察读取端,该源从管道读取数据并将其附加到textview.
NSPipe* pipe = [NSPipe pipe];
NSFileHandle* pipeReadHandle = [pipe fileHandleForReading];
dup2([[pipe fileHandleForWriting] fileDescriptor],fileno(stdout));
dispatch_source_t source = dispatch_source_create(disPATCH_SOURCE_TYPE_READ,[pipeReadHandle fileDescriptor],dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAULT,0));
dispatch_source_set_event_handler(source,^{
    void* data = malloc(4096);
    ssize_t readResult = 0;
    do
    {
        errno = 0;
        readResult = read([pipeReadHandle fileDescriptor],data,4096);
    } while (readResult == -1 && errno == EINTR);
    if (readResult > 0)
    {
        //AppKit UI should only be updated from the main thread
        dispatch_async(dispatch_get_main_queue(),^{
            Nsstring* stdOutString = [[Nsstring alloc] initWithBytesNocopy:data length:readResult encoding:NSUTF8StringEncoding freeWhenDone:YES];
            NSAttributedString* stdOutAttributedString = [[NSAttributedString alloc] initWithString:stdOutString];
            [self.logView.textStorage appendAttributedString:stdOutAttributedString];
        });
    }
    else{free(data);}
});
dispatch_resume(source);

NSLog(@“…”)不输出到stdout – 它打印到stderr.如果要将其重定向到文本视图,请更改

dup2([[pipe fileHandleForWriting] fileDescriptor],fileno(stdout));

dup2([[pipe fileHandleForWriting] fileDescriptor],fileno(stderr));

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...