Skip navigation.
 
mlRe: printf to cocoa
FROM : Heinrich Giesen
DATE : Fri Apr 29 17:53:03 2005

On 28.04.2005, at 03:55, Adam wrote:

>  Is
> there any way to redirect what is sent to printf to an NSTextView? Or
> somehow get it to display in my cocoa GUI?



This question is often asked and you find a lot of hints in this group.
The solution I like very much and use in my applications I saw first in
http://www.cocoabuilder.com/archive/message/2004/6/22/110294
by Gerriet M. Denkmann.

After some changes in the code I do this:

in an appropriate .m file declare:

typedef int File_Writer_t(void *, const char *, int);
NSTextView    *stdoutConsole = nil;
File_Writer_t *originalStdout;

and the three functions:

static int myStdoutWriter( void *inFD, const char *buffer, int size )
{
    NSString *tmp = [[NSString alloc] initWithCString:buffer
length:size];
    int length = [[stdoutConsole string] length];
    NSRange range = NSMakeRange(length,0);
   
    [stdoutConsole replaceCharactersInRange:range withString:tmp];
    [stdoutConsole scrollRangeToVisible:range];
   
    [tmp release] ;
    return size ;
}


- (void) setNewStdout
{
    originalStdout = stdout->_write;
    stdout->_write = &myStdoutWriter ;
}

- (void) resetNewStdout
{
    stderr->_write = originalStdout ;
}

You activate these functions with:

- (void) applicationDidFinishLaunching:(NSNotification *)aNotification
{
    . . . . .
   stdoutConsole = console;    // console is the NSTextView to write in
   [self setNewStdout];
}

For programming in Cocoa you need not know anything about Unix
but it helps a lot. And there is nothing bad to use what Unix offers.

(see /usr/inclide/stdio.h)

(You can of course do the same for stderr)


--
Heinrich Giesen

email: <email_removed>

Related mailsAuthorDate
mlprintf to cocoa Adam Apr 28, 02:27
mlRe: printf to cocoa John Stiles Apr 28, 03:04
mlRe: printf to cocoa Heinrich Giesen Apr 29, 17:53