我在Xcode中读取控制台的代码总是出现错误:
读取:错误的文件描述符
#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);
}
}
这有什么问题?
最佳答案
您无法阅读stderr,但可以将其重定向。像这样:
- (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];
}
关于objective-c - 尝试读取Xcode的控制台输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6169695/