Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to read Xcode's console output

My code to read the console in Xcode always gives an error :

read: Bad file descriptor

#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"Some text..."); 

    int fd;
    char ch[1024];
    fd = read(stderr,ch, sizeof(ch));
    if(fd == -1) {
        perror("read");
    } else {
        NSLog(@"Data Read : %s", ch);

    }

}

What is wrong with this?

like image 211
Biranchi Avatar asked Dec 10 '25 09:12

Biranchi


1 Answers

You can't read stderr, but you can redirect it. Like this:

- (void) redirectStandardError
{
    stderrPipe = [NSPipe pipe];
    stderrPipeReadHandle = [stderrPipe fileHandleForReading];
    dup2( [[stderrPipe fileHandleForWriting] fileDescriptor], fileno(stderr));

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(handleNotification:) 
                                                 name:NSFileHandleReadCompletionNotification 
                                               object:stderrPipeReadHandle];
    [stderrPipeReadHandle readInBackgroundAndNotify];
}

- (void) handleNotification:(NSNotification*)notification {
    [stderrPipeReadHandle readInBackgroundAndNotify];

    NSString* str = [[NSString alloc] initWithData:[[notification userInfo] objectForKey:NSFileHandleNotificationDataItem] encoding:NSASCIIStringEncoding];

    // Do something with str...

    [str release];
}
like image 189
zpasternack Avatar answered Dec 12 '25 23:12

zpasternack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!